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/test-suite/src/test/java/io/hyperfoil/test/entity/Fleet.java
test-suite/src/test/java/io/hyperfoil/test/entity/Fleet.java
package io.hyperfoil.test.entity; import java.util.ArrayList; import java.util.Collection; public class Fleet { private String name; private Collection<String> bases = new ArrayList<>(); private Collection<Ship> ships = new ArrayList<>(); public Fleet(String name) { this.name = name; } public Fleet addShip(Ship ship) { ships.add(ship); return this; } public Fleet addBase(String base) { bases.add(base); return this; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Collection<String> getBases() { return bases; } public void setBases(Collection<String> bases) { this.bases = bases; } public Collection<Ship> getShips() { return ships; } public void setShips(Collection<Ship> ships) { this.ships = ships; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/test-suite/src/test/java/io/hyperfoil/test/entity/Ship.java
test-suite/src/test/java/io/hyperfoil/test/entity/Ship.java
package io.hyperfoil.test.entity; import java.util.ArrayList; import java.util.Collection; public class Ship { private String name; private long dwt; private Collection<CrewMember> crew = new ArrayList<>(); public Ship(String name) { this.name = name; } public Ship dwt(long dwt) { this.dwt = dwt; return this; } public Ship addCrew(CrewMember crewMember) { crew.add(crewMember); return this; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getDwt() { return dwt; } public void setDwt(long dwt) { this.dwt = dwt; } public Collection<CrewMember> getCrew() { return crew; } public void setCrew(Collection<CrewMember> crew) { this.crew = crew; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/test/java/io/hyperfoil/api/collection/LimitedPoolTest.java
api/src/test/java/io/hyperfoil/api/collection/LimitedPoolTest.java
package io.hyperfoil.api.collection; import java.util.ArrayDeque; import java.util.concurrent.ThreadLocalRandom; import org.junit.jupiter.api.Test; public class LimitedPoolTest { @Test public void test() { final int size = 16; LimitedPool<Integer> pool = new LimitedPool<>(size, () -> 0); ArrayDeque<Integer> queue = new ArrayDeque<>(size); for (int i = 0; i < 10000; ++i) { if (queue.isEmpty()) { queue.push(pool.acquire()); } else if (queue.size() == size || ThreadLocalRandom.current().nextBoolean()) { pool.release(queue.poll()); } else { queue.push(pool.acquire()); } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/impl/CollectingVisitor.java
api/src/main/java/io/hyperfoil/impl/CollectingVisitor.java
package io.hyperfoil.impl; import java.lang.reflect.Array; import java.lang.reflect.Type; import java.util.Collection; import java.util.IdentityHashMap; import java.util.Map; import io.hyperfoil.api.config.Visitor; public abstract class CollectingVisitor<T> implements Visitor { private final Map<Object, Object> seen = new IdentityHashMap<>(); private final Class<T> clazz; public CollectingVisitor(Class<T> clazz) { this.clazz = clazz; } public void visit(Object root) { visit(null, root, null); } @Override public boolean visit(String name, Object value, Type fieldType) { if (value == null) { return false; } else if (seen.put(value, value) != null) { return false; } else if (clazz.isInstance(value)) { if (process(clazz.cast(value))) { ReflectionAcceptor.accept(value, this); } } else if (value instanceof Collection) { ((Collection<?>) value).forEach(item -> visit(null, item, null)); } else if (value instanceof Map) { ((Map<?, ?>) value).forEach((k, v) -> visit(null, v, null)); } else if (ReflectionAcceptor.isScalar(value)) { return false; } else if (value.getClass().isArray()) { int length = Array.getLength(value); for (int i = 0; i < length; ++i) { visit(null, Array.get(value, i), null); } } else { ReflectionAcceptor.accept(value, this); } // the return value doesn't matter here return false; } protected abstract boolean process(T value); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/impl/ReflectionAcceptor.java
api/src/main/java/io/hyperfoil/impl/ReflectionAcceptor.java
package io.hyperfoil.impl; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.stream.Stream; import io.hyperfoil.api.config.Visitor; import io.hyperfoil.api.session.ReadAccess; public class ReflectionAcceptor { private static final Class<?>[] BOXING_TYPES = new Class[] { Boolean.class, Integer.class, Long.class, Double.class, Byte.class, Character.class, Short.class, Float.class, Void.class }; public static int accept(Object target, Visitor visitor) { int written = 0; for (Field f : getAllFields(target)) { if (f.getDeclaringClass().getModule() != ReflectionAcceptor.class.getModule()) { // we have wandered astray continue; } if (f.trySetAccessible()) { try { Visitor.Invoke invoke = f.getAnnotation(Visitor.Invoke.class); if (invoke == null) { Object value = f.get(target); if (visitor.visit(f.getName(), value, f.getGenericType())) { written++; } } else { Method method = f.getDeclaringClass().getMethod(invoke.method()); method.setAccessible(true); Object value = method.invoke(target); if (visitor.visit(f.getName(), value, method.getGenericReturnType())) { written++; } } } catch (IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { throw new RuntimeException(e); } } } return written; } private static List<Field> getAllFields(Object target) { Class<?> cls = target.getClass(); List<Field> fields = new ArrayList<>(); while (cls != null && cls != Object.class) { for (Field f : cls.getDeclaredFields()) { if (Modifier.isStatic(f.getModifiers()) || f.isSynthetic() || f.isAnnotationPresent(Visitor.Ignore.class)) { // ignored fields } else if ("parent".equals(f.getName())) { // ignored as well } else { fields.add(f); } } cls = cls.getSuperclass(); } fields.sort(Comparator.comparing(Field::getName)); return fields; } public static boolean isScalar(Object value) { if (value == null) { return true; } if (value instanceof CharSequence || value instanceof ReadAccess) { return true; } Class<?> cls = value.getClass(); // the superclass.isEnum is needed for enums with extra methods - these become non-enum somehow return cls.isPrimitive() || cls.isEnum() || (cls.getSuperclass() != null && cls.getSuperclass().isEnum()) || Stream.of(BOXING_TYPES).anyMatch(c -> c == cls); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/impl/FutureSupplier.java
api/src/main/java/io/hyperfoil/impl/FutureSupplier.java
package io.hyperfoil.impl; import io.hyperfoil.function.SerializableSupplier; public class FutureSupplier<T> implements SerializableSupplier<T> { private T object; public void set(T object) { assert this.object == null; assert object != null; this.object = object; } @Override public T get() { return object; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/impl/Util.java
api/src/main/java/io/hyperfoil/impl/Util.java
package io.hyperfoil.impl; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.charset.CharsetEncoder; import java.nio.charset.CoderResult; import java.nio.charset.StandardCharsets; import java.util.Arrays; import java.util.BitSet; import java.util.HashSet; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.netty.buffer.ByteBuf; import io.netty.util.AsciiString; public class Util { public static final CompletableFuture<Void> COMPLETED_VOID_FUTURE = CompletableFuture.completedFuture(null); private static final NumberFormatException NUMBER_FORMAT_EXCEPTION = new NumberFormatException(); private static final int[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' }; private Util() { } public static boolean compareIgnoreCase(byte b1, byte b2) { return b1 == b2 || toUpperCase(b1) == toUpperCase(b2) || toLowerCase(b1) == toLowerCase(b2); } public static byte toLowerCase(byte b) { return b >= 'A' && b <= 'Z' ? (byte) (b + 32) : b; } public static byte toUpperCase(byte b) { return b >= 'a' && b <= 'z' ? (byte) (b - 32) : b; } /** * Pretty prints timeNanos in 9 spaces * * @param timeNanos Time in nanoseconds. * @return Formatted string. */ public static String prettyPrintNanosFixed(long timeNanos) { return prettyPrintNanos(timeNanos, "6", true); } /** * Pretty prints time * * @param timeNanos Time in nanoseconds. * @param width Number of characters in the number, as string * @param spaceBeforeUnit Separate number and unit with a space. * @return Formatted string. */ public static String prettyPrintNanos(long timeNanos, String width, boolean spaceBeforeUnit) { String space = spaceBeforeUnit ? " " : ""; if (timeNanos < 1000) { return String.format("%" + width + "d%sns", timeNanos, space); } else if (timeNanos < 1000_000) { return String.format("%" + width + ".2f%sμs", timeNanos / 1000d, space); } else if (timeNanos < 1000_000_000) { return String.format("%" + width + ".2f%sms", timeNanos / 1000_000d, space); } else { return String.format("%" + width + ".2f%ss ", timeNanos / 1000_000_000d, space); } } public static String prettyPrintNanos(long timeNanos) { return prettyPrintNanos(timeNanos, "", true); } public static String toString(ByteBuf buf, int offset, int length) { if (buf.hasArray()) { return new String(buf.array(), buf.arrayOffset() + offset, length, StandardCharsets.UTF_8); } else { byte[] strBytes = new byte[length]; buf.getBytes(offset, strBytes, 0, length); return new String(strBytes, StandardCharsets.UTF_8); } } public static boolean isLatin(CharSequence cs) { final int len = cs.length(); if (len == 0 || cs instanceof AsciiString) { return true; } // TODO in a future JDK it can read the coder bits of String final int longRounds = len >>> 3; int off = 0; for (int i = 0; i < longRounds; i++) { final long batch1 = (((long) cs.charAt(off)) << 48) | (((long) cs.charAt(off + 2)) << 32) | cs.charAt(off + 4) << 16 | cs.charAt(off + 6); final long batch2 = (((long) cs.charAt(off + 1)) << 48) | (((long) cs.charAt(off + 3)) << 32) | cs.charAt(off + 5) << 16 | cs.charAt(off + 7); // 0xFF00 is 0b1111111100000000: it masks whatever exceed 255 // Biggest latin is 255 -> 0b11111111 if (((batch1 | batch2) & 0xff00_ff00_ff00_ff00L) != 0) { return false; } off += Long.BYTES; } final int byteRounds = len & 7; if (byteRounds > 0) { for (int i = 0; i < byteRounds; i++) { final char c = cs.charAt(off + i); if (c > 255) { return false; } } } return true; } public static boolean isAscii(ByteBuf cs, int offset, int len) { if (len == 0) { return true; } // maybe in a future JDK we can read the coder bits of String final int longRounds = len >>> 3; int off = offset; final boolean usLE = ByteOrder.nativeOrder() == ByteOrder.LITTLE_ENDIAN; for (int i = 0; i < longRounds; i++) { final long batch = usLE ? cs.getLongLE(off) : cs.getLong(off); // 0x80 is 0b1000000: it masks whatever exceed 127 // Biggest US-ASCII is 127 -> 0b01111111 if ((batch & 0x80_80_80_80_80_80_80_80L) != 0) { return false; } off += Long.BYTES; } final int byteRounds = len & 7; if (byteRounds > 0) { for (int i = 0; i < byteRounds; i++) { final byte c = cs.getByte(off + i); if (c < 0) { return false; } } } return true; } public static AsciiString toAsciiString(ByteBuf buf, int offset, int length) { final byte[] bytes = new byte[length]; buf.getBytes(offset, bytes); return new AsciiString(bytes, false); } public static ByteBuf string2byteBuf(CharSequence str, ByteBuf buffer) { // TODO: allocations everywhere but at least not the bytes themselves... CharBuffer input = CharBuffer.wrap(str); ByteBuffer output = buffer.nioBuffer(buffer.writerIndex(), buffer.capacity() - buffer.writerIndex()); CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder(); int accumulatedBytes = buffer.writerIndex(); for (;;) { CoderResult result = encoder.encode(input, output, true); if (result.isError()) { throw new RuntimeException("Cannot encode: " + result + ", string is " + str); } else if (result.isUnderflow()) { buffer.writerIndex(accumulatedBytes + output.position()); return buffer; } else if (result.isOverflow()) { buffer.capacity(buffer.capacity() * 2); int writtenBytes = output.position(); accumulatedBytes += writtenBytes; output = buffer.nioBuffer(accumulatedBytes, buffer.capacity() - accumulatedBytes); } else { throw new IllegalStateException(); } } } public static String explainCauses(Throwable e) { StringBuilder causes = new StringBuilder(); Set<Throwable> reported = new HashSet<>(); while (e != null && !reported.contains(e)) { if (causes.length() != 0) { causes.append(": "); } causes.append(e.getMessage()); reported.add(e); e = e.getCause(); } return causes.toString(); } public static boolean regionMatchesIgnoreCase(CharSequence a, int aoffset, CharSequence b, int boffset, int length) { if (a instanceof String && b instanceof String) { return ((String) a).regionMatches(true, aoffset, (String) b, boffset, length); } if (aoffset < 0 || boffset < 0) { return false; } else if (aoffset + length > a.length() || boffset + length > b.length()) { return false; } while (length-- > 0) { char c1 = a.charAt(aoffset++); char c2 = b.charAt(boffset++); if (c1 == c2) { continue; } char u1 = Character.toUpperCase(c1); char u2 = Character.toUpperCase(c2); if (u1 == u2) { continue; } if (Character.toLowerCase(u1) != Character.toLowerCase(u2)) { return false; } } return true; } public static boolean regionMatches(CharSequence a, int aoffset, CharSequence b, int boffset, int length) { if (a instanceof String && b instanceof String) { return ((String) a).regionMatches(aoffset, (String) b, boffset, length); } if (aoffset < 0 || boffset < 0) { return false; } else if (aoffset + length > a.length() || boffset + length > b.length()) { return false; } while (length-- > 0) { char c1 = a.charAt(aoffset++); char c2 = b.charAt(boffset++); if (c1 != c2) { return false; } } return true; } public static boolean startsWith(CharSequence sequence, int offset, CharSequence prefix) { return regionMatches(sequence, offset, prefix, 0, prefix.length()); } public static int pow(int base, int exp) { int res = 1; while (exp-- > 0) res *= base; return res; } public static long parseLong(ByteBuf data, int offset, int length) { long value = 0; int i = offset; while (Character.isWhitespace(data.getByte(i))) ++i; byte sign = data.getByte(i); if (sign == '-' || sign == '+') ++i; while (Character.isWhitespace(data.getByte(i))) ++i; while (length > 0 && Character.isWhitespace(data.getByte(offset + length - 1))) --length; for (; i < offset + length; ++i) { byte digit = data.getByte(i); if (digit < '0' || digit > '9') { throw NUMBER_FORMAT_EXCEPTION; } value *= 10; value += digit - '0'; } return sign == '-' ? -value : value; } public static boolean isParamConvertible(Class<?> type) { return type == String.class || type == CharSequence.class || type == Object.class || type.isPrimitive() || type.isEnum(); } public static String prettyPrintObject(Object value) { if (value instanceof byte[]) { byte[] bytes = (byte[]) value; if (bytes.length == 0) { return ""; } StringBuilder sb = new StringBuilder("["); sb.append((char) HEX[(bytes[0] >> 4)]); sb.append((char) HEX[(bytes[0] & 0xF)]); int length = Math.min(32, bytes.length); for (int i = 1; i < length; ++i) { sb.append(", "); sb.append((char) HEX[(bytes[i] >> 4)]); sb.append((char) HEX[(bytes[i] & 0xF)]); } if (bytes.length > 32) { sb.append(", ... (total length: ").append(bytes.length).append(")"); } sb.append("]="); sb.append(new String(bytes, 0, Math.min(bytes.length, 32), StandardCharsets.UTF_8)); if (bytes.length > 32) { sb.append("..."); } return sb.toString(); } else if (value instanceof Object[]) { return Arrays.toString((Object[]) value); } else { return String.valueOf(value); } } public static boolean hasPrefix(ByteBuf data, int offset, int length, byte[] prefix) { int i = 0; if (length < prefix.length) { return false; } for (; i < prefix.length; i++) { if (data.getByte(offset + i) != prefix[i]) { return false; } } return true; } public static byte[] serialize(Benchmark benchmark) throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); try (ObjectOutputStream outputStream = new ObjectOutputStream(byteArrayOutputStream)) { outputStream.writeObject(benchmark); } return byteArrayOutputStream.toByteArray(); } public static Benchmark deserialize(byte[] bytes) throws IOException, ClassNotFoundException { try (ObjectInputStream input = new ObjectInputStream(new ByteArrayInputStream(bytes))) { return (Benchmark) input.readObject(); } } private static ByteArrayOutputStream toByteArrayOutputStream(InputStream stream) throws IOException { ByteArrayOutputStream result = new ByteArrayOutputStream(); byte[] buffer = new byte[1024]; int length; while ((length = stream.read(buffer)) != -1) { result.write(buffer, 0, length); } stream.close(); return result; } public static byte[] toByteArray(InputStream stream) throws IOException { return toByteArrayOutputStream(stream).toByteArray(); } public static String toString(InputStream stream) throws IOException { return toByteArrayOutputStream(stream).toString(StandardCharsets.UTF_8.name()); } public static long parseLong(CharSequence string) { return parseLong(string, 0, string.length(), 0); } public static long parseLong(CharSequence string, int begin, int end) { return parseLong(string, begin, end, 0); } public static long parseLong(CharSequence string, int begin, int end, long defaultValue) { long value = 0; int i = begin; char sign = string.charAt(begin); if (sign == '-' || sign == '+') ++i; for (; i < end; ++i) { int digit = string.charAt(i); if (digit < '0' || digit > '9') return defaultValue; value *= 10; value += digit - '0'; } return sign == '-' ? -value : value; } public static long parseToNanos(String time) { TimeUnit unit; String prefix; if (time.endsWith("ms")) { unit = TimeUnit.MILLISECONDS; prefix = time.substring(0, time.length() - 2); } else if (time.endsWith("us")) { unit = TimeUnit.MICROSECONDS; prefix = time.substring(0, time.length() - 2); } else if (time.endsWith("ns")) { unit = TimeUnit.NANOSECONDS; prefix = time.substring(0, time.length() - 2); } else if (time.endsWith("s")) { unit = TimeUnit.SECONDS; prefix = time.substring(0, time.length() - 1); } else if (time.endsWith("m")) { unit = TimeUnit.MINUTES; prefix = time.substring(0, time.length() - 1); } else if (time.endsWith("h")) { unit = TimeUnit.HOURS; prefix = time.substring(0, time.length() - 1); } else { throw new BenchmarkDefinitionException("Unknown time unit: " + time); } return unit.toNanos(Long.parseLong(prefix.trim())); } public static long parseToMillis(String time) { time = time.trim(); TimeUnit unit; String prefix; switch (time.charAt(time.length() - 1)) { case 's': if (time.endsWith("ms")) { unit = TimeUnit.MILLISECONDS; prefix = time.substring(0, time.length() - 2).trim(); } else { unit = TimeUnit.SECONDS; prefix = time.substring(0, time.length() - 1).trim(); } break; case 'm': unit = TimeUnit.MINUTES; prefix = time.substring(0, time.length() - 1).trim(); break; case 'h': unit = TimeUnit.HOURS; prefix = time.substring(0, time.length() - 1).trim(); break; default: unit = TimeUnit.SECONDS; prefix = time; break; } return unit.toMillis(Long.parseLong(prefix)); } public static ThreadFactory daemonThreadFactory(String prefix) { return new ThreadFactory() { private final AtomicInteger counter = new AtomicInteger(); @Override public Thread newThread(Runnable task) { Thread thread = new Thread(task, prefix + "-" + counter.incrementAndGet()); thread.setDaemon(true); return thread; } }; } private static class URLEncoding { private static final BitSet DONT_NEED_ENCODING = new BitSet(); static { for (int i = 'a'; i <= 'z'; i++) { DONT_NEED_ENCODING.set(i); } for (int i = 'A'; i <= 'Z'; i++) { DONT_NEED_ENCODING.set(i); } for (int i = '0'; i <= '9'; i++) { DONT_NEED_ENCODING.set(i); } DONT_NEED_ENCODING.set('-'); DONT_NEED_ENCODING.set('_'); DONT_NEED_ENCODING.set('.'); DONT_NEED_ENCODING.set('*'); } } public static void urlEncode(String string, ByteBuf buf) { // TODO: more efficient implementation without allocation byte[] bytes = string.getBytes(StandardCharsets.UTF_8); for (byte b : bytes) { if (b >= 0 && URLEncoding.DONT_NEED_ENCODING.get(b)) { buf.ensureWritable(1); buf.writeByte(b); } else if (b == ' ') { buf.ensureWritable(1); buf.writeByte('+'); } else { buf.ensureWritable(3); buf.writeByte('%'); buf.writeByte(HEX[(b >> 4) & 0xF]); buf.writeByte(HEX[b & 0xF]); } } } public static String prettyPrintData(double value) { double scaled; String suffix; if (value >= 1024 * 1024 * 1024) { scaled = (double) value / (1024 * 1024 * 1024); suffix = "GB"; } else if (value >= 1024 * 1024) { scaled = (double) value / (1024 * 1024); suffix = "MB"; } else if (value >= 1024) { scaled = (double) value / 1024; suffix = "kB"; } else { scaled = value; suffix = "B "; } return String.format("%6.2f%s", scaled, suffix); } private static final int[] SIZE_TABLE = new int[] { 1_000_000_000, 100_000_000, 10_000_000, 1_000_000, 100_000, 10_000, 1000, 100, 10 }; public static void intAsText2byteBuf(int value, ByteBuf buf) { if (value < 0) { buf.writeByte('-'); value = -value; } int i = 0; for (; i < SIZE_TABLE.length; ++i) { if (value >= SIZE_TABLE[i]) break; } for (; i < SIZE_TABLE.length; ++i) { int q = value / SIZE_TABLE[i]; assert q >= 0 && q <= 9; buf.writeByte('0' + q); value -= q * SIZE_TABLE[i]; } assert value >= 0 && value <= 9; buf.writeByte('0' + value); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/impl/StepCatalogFactory.java
api/src/main/java/io/hyperfoil/impl/StepCatalogFactory.java
package io.hyperfoil.impl; import io.hyperfoil.api.config.BaseSequenceBuilder; import io.hyperfoil.api.config.Step; public interface StepCatalogFactory { Class<? extends Step.Catalog> clazz(); Step.Catalog create(BaseSequenceBuilder<?> sequenceBuilder); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/BenchmarkExecutionException.java
api/src/main/java/io/hyperfoil/api/BenchmarkExecutionException.java
package io.hyperfoil.api; public class BenchmarkExecutionException extends Exception { public BenchmarkExecutionException(String message) { super(message); } public BenchmarkExecutionException(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/api/src/main/java/io/hyperfoil/api/Version.java
api/src/main/java/io/hyperfoil/api/Version.java
package io.hyperfoil.api; import java.net.URL; import java.util.jar.Attributes; import java.util.jar.Manifest; import org.apache.logging.log4j.LogManager; public class Version { public static final String VERSION; public static final String COMMIT_ID; static { String version = "unknown"; String commitId = "unknown"; try { String classPath = Version.class.getResource(Version.class.getSimpleName() + ".class").toString(); if (classPath.startsWith("jar")) { String manifestPath = classPath.substring(0, classPath.lastIndexOf("!") + 1) + "/META-INF/MANIFEST.MF"; Manifest manifest = null; manifest = new Manifest(new URL(manifestPath).openStream()); Attributes attr = manifest.getMainAttributes(); commitId = attr.getValue("Scm-Revision"); version = attr.getValue("Implementation-Version"); } } catch (Throwable e) { LogManager.getLogger(Version.class).error("Cannot find version info.", e); } finally { VERSION = version; COMMIT_ID = commitId; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/processor/Processor.java
api/src/main/java/io/hyperfoil/api/processor/Processor.java
package io.hyperfoil.api.processor; import java.io.Serializable; import java.util.function.Function; import io.hyperfoil.api.config.BuilderBase; import io.hyperfoil.api.config.IncludeBuilders; import io.hyperfoil.api.session.Action; import io.hyperfoil.api.session.Session; import io.netty.buffer.ByteBuf; public interface Processor extends Serializable { static Processor.Builder adapt(Action.Builder builder) { return new ActionBuilderAdapter(builder); } /** * Invoked before we record first value from given response. * * @param session Request. */ default void before(Session session) { } void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart); /** * Invoked after we record the last value from given response. * * @param session Request. */ default void after(Session session) { } default void ensureDefragmented(boolean isLastPart) { if (!isLastPart) { throw new IllegalStateException("This processor expects defragmented data."); } } @IncludeBuilders(@IncludeBuilders.Conversion(from = Action.Builder.class, adapter = Processor.ActionBuilderConverter.class)) interface Builder extends BuilderBase<Builder> { Processor build(boolean fragmented); } abstract class BaseDelegating implements Processor { protected final Processor delegate; protected BaseDelegating(Processor delegate) { this.delegate = delegate; } @Override public void before(Session session) { delegate.before(session); } @Override public void after(Session session) { delegate.after(session); } } class ActionAdapter implements Processor { private final Action action; public ActionAdapter(Action action) { this.action = action; } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { // Action should be performed only when the last chunk arrives if (!isLastPart) { return; } action.run(session); } } class ActionBuilderConverter implements Function<Action.Builder, Processor.Builder> { @Override public Processor.Builder apply(Action.Builder builder) { return new ActionBuilderAdapter(builder); } } class ActionBuilderAdapter implements Processor.Builder { private final Action.Builder builder; public ActionBuilderAdapter(Action.Builder builder) { this.builder = builder; } @Override public Processor.Builder copy(Object newParent) { return new ActionBuilderAdapter(builder.copy(null)); } @Override public Processor build(boolean fragmented) { return new ActionAdapter(builder.build()); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/processor/Transformer.java
api/src/main/java/io/hyperfoil/api/processor/Transformer.java
package io.hyperfoil.api.processor; import java.io.Serializable; import io.hyperfoil.api.config.BuilderBase; import io.hyperfoil.api.session.Session; import io.netty.buffer.ByteBuf; public interface Transformer extends Serializable { default void before(Session session) { } void transform(Session session, ByteBuf in, int offset, int length, boolean lastFragment, ByteBuf out); default void after(Session session) { } interface Builder extends BuilderBase<Builder> { Transformer build(boolean fragmented); } class ProcessorAdapter implements Transformer { private final Processor delegate; public ProcessorAdapter(Processor delegate) { this.delegate = delegate; } @Override public void before(Session session) { delegate.before(session); } @Override public void transform(Session session, ByteBuf input, int offset, int length, boolean isLastFragment, ByteBuf output) { delegate.process(session, input, offset, length, isLastFragment); } @Override public void after(Session session) { delegate.after(session); } } abstract class BaseDelegating implements Transformer { protected final Transformer delegate; protected BaseDelegating(Transformer delegate) { this.delegate = delegate; } @Override public void before(Session session) { delegate.before(session); } @Override public void after(Session session) { delegate.after(session); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/processor/RawBytesHandler.java
api/src/main/java/io/hyperfoil/api/processor/RawBytesHandler.java
package io.hyperfoil.api.processor; import java.io.Serializable; import io.hyperfoil.api.config.BuilderBase; import io.hyperfoil.api.connection.Request; import io.netty.buffer.ByteBuf; public interface RawBytesHandler extends Serializable { void onRequest(Request request, ByteBuf buf, int offset, int length); void onResponse(Request request, ByteBuf buf, int offset, int length, boolean isLastPart); interface Builder extends BuilderBase<Builder> { RawBytesHandler build(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/connection/Request.java
api/src/main/java/io/hyperfoil/api/connection/Request.java
package io.hyperfoil.api.connection; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.session.SequenceInstance; import io.hyperfoil.api.session.Session; import io.hyperfoil.api.statistics.Statistics; import io.netty.util.concurrent.Future; import io.netty.util.concurrent.GenericFutureListener; import io.netty.util.concurrent.ScheduledFuture; public abstract class Request implements Callable<Void>, GenericFutureListener<Future<Void>> { private static final Logger log = LogManager.getLogger(Request.class); private static final GenericFutureListener<Future<Object>> FAILURE_LISTENER = future -> { if (!future.isSuccess() && !future.isCancelled()) { log.error("Timeout task failed", future.cause()); } }; public final Session session; private long startTimestampMillis; private long startTimestampNanos; private SequenceInstance sequence; private SequenceInstance completionSequence; private Statistics statistics; private ScheduledFuture<?> timeoutFuture; private Connection connection; private Status status = Status.IDLE; private Result result = Result.VALID; public Request(Session session) { this.session = session; } /** * This method works as timeout handler */ @Override public Void call() { int uniqueId = session == null ? -1 : session.uniqueId(); log.warn("#{} Request timeout, closing connection {}", uniqueId, connection); timeoutFuture = null; if (status != Status.COMPLETED) { result = Result.TIMED_OUT; statistics.incrementTimeouts(startTimestampMillis); if (connection == null) { log.warn("#{} connection is already null", uniqueId); } else { connection.close(); } // handleThrowable sets the request completed } else { log.trace("#{} Request {} is already completed.", uniqueId, this); } return null; } public void start(SequenceInstance sequence, Statistics statistics) { this.startTimestampMillis = System.currentTimeMillis(); this.startTimestampNanos = System.nanoTime(); this.sequence = sequence; // The reason for using separate sequence reference just for the sake of decrementing // its counter is that the request sequence might be overridden (wrapped) through // `unsafeEnterSequence` when the request is cancelled (e.g. because the session // is being stopped). In that case we would decrement counters on a wrong sequence. this.completionSequence = sequence.incRefCnt(); this.statistics = statistics; this.status = Status.RUNNING; this.result = Result.VALID; } public void attach(Connection connection) { this.connection = connection; } public Status status() { return status; } public boolean isValid() { return result == Result.VALID; } public void markInvalid() { result = Result.INVALID; } public void setCompleting() { status = Status.COMPLETING; } public boolean isRunning() { return status == Status.RUNNING; } public boolean isCompleted() { return status == Status.COMPLETED || status == Status.IDLE; } public void setCompleted() { if (timeoutFuture != null) { timeoutFuture.cancel(false); timeoutFuture = null; } connection = null; sequence = null; // handleEnd may indirectly call handleThrowable which calls setCompleted first if (status != Status.IDLE) { status = Status.COMPLETED; completionSequence.decRefCnt(session); completionSequence = null; } } public Connection connection() { return connection; } public SequenceInstance sequence() { return sequence; } public Statistics statistics() { return statistics; } public void recordResponse(long endTimestampNanos) { statistics.recordResponse(startTimestampMillis, endTimestampNanos - startTimestampNanos); } public long startTimestampMillis() { return startTimestampMillis; } public long startTimestampNanos() { return startTimestampNanos; } public void setTimeout(long timeout, TimeUnit timeUnit) { timeoutFuture = session.executor().schedule(this, timeout, timeUnit); timeoutFuture.addListener(FAILURE_LISTENER); } @Override public void operationComplete(Future<Void> future) { // This is called when the request is written on the wire // It doesn't make sense to throw any exceptions from this method // since DefaultPromise.notifyListener0 would swallow them with a warning. if (!future.isSuccess()) { log.error("Failed to write request {} to {}", this, connection); if (connection != null) { connection.close(); } } } public abstract void release(); public void enter() { session.currentSequence(sequence); session.currentRequest(this); } public void exit() { session.currentSequence(null); session.currentRequest(null); } /* * Use this method very cautiously! */ public void unsafeEnterSequence(SequenceInstance sequence) { this.sequence = sequence; } protected void setIdle() { status = Status.IDLE; } @Override public String toString() { return "(#" + session.uniqueId() + ", " + status + ", " + result + ")"; } public enum Result { VALID, INVALID, TIMED_OUT, } public enum Status { IDLE, // in pool RUNNING, COMPLETING, COMPLETED, } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/connection/ResponseHandlers.java
api/src/main/java/io/hyperfoil/api/connection/ResponseHandlers.java
package io.hyperfoil.api.connection; public interface ResponseHandlers<R extends Request> { void handleThrowable(R request, Throwable throwable); /** * @param request Request. * @param executed True if the request was sent to the server, false if it was intercepted and cancelled. */ void handleEnd(R request, boolean executed); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/connection/Connection.java
api/src/main/java/io/hyperfoil/api/connection/Connection.java
package io.hyperfoil.api.connection; import java.io.IOException; import io.netty.channel.ChannelHandlerContext; public interface Connection { IOException CLOSED_EXCEPTION = new IOException("Connection was unexpectedly closed."); IOException SELF_CLOSED_EXCEPTION = new IOException("Connection was closed by us."); ChannelHandlerContext context(); void onAcquire(); boolean isAvailable(); int inFlight(); /** * This is an external request to close the connection */ void close(); /** * Invoked by the pool when the connection got closed. */ void setClosed(); boolean isOpen(); boolean isClosed(); String host(); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/collection/Lookup.java
api/src/main/java/io/hyperfoil/api/collection/Lookup.java
package io.hyperfoil.api.collection; import java.lang.reflect.Array; import java.util.function.Supplier; /** * Primitive hashmap with limited insertion capability. Provides cached arrays with all values. */ public class Lookup<K, V> { final Class<V> clazz; final Supplier<V> factory; Object[] keys; V[] values; V[] array; int size; public Lookup(Class<V> clazz, Supplier<V> factory) { this.clazz = clazz; this.factory = factory; this.keys = new Object[4]; this.values = newArray(4); } public V get(K key) { int mask = keys.length - 1; int slot = key.hashCode() & mask; for (;;) { Object k2 = keys[slot]; if (k2 == null) { return null; } else if (k2.equals(key)) { return values[slot]; } slot = (slot + 1) & mask; } } public V reserve(K key) { V existing = get(key); if (existing != null) { return existing; } // we aim at 50% occupancy at most if (++size * 2 > values.length) { int newSize = keys.length * 2; Object[] newKeys = new Object[newSize]; V[] newValues = newArray(newSize); int mask = newSize - 1; for (int i = 0; i < keys.length; ++i) { Object k = keys[i]; if (k != null) { insert(newKeys, newValues, mask, k, values[i]); } } keys = newKeys; values = newValues; } V newValue = factory.get(); insert(keys, values, keys.length - 1, key, newValue); array = null; return newValue; } private void insert(Object[] newKeys, V[] newValues, int mask, Object k, V v) { int slot = k.hashCode() & mask; Object otherKey; while ((otherKey = newKeys[slot]) != null) { assert !otherKey.equals(k); slot = (slot + 1) & mask; } newKeys[slot] = k; newValues[slot] = v; } @SuppressWarnings("unchecked") private V[] newArray(int size) { return (V[]) Array.newInstance(clazz, size); } /** * @return Cached map with the values. Should not be modified! */ public V[] array() { if (array == null) { array = newArray(size); int i = 0; for (V v : values) { if (v != null) { array[i++] = v; } } } return array; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/collection/ElasticPool.java
api/src/main/java/io/hyperfoil/api/collection/ElasticPool.java
package io.hyperfoil.api.collection; /** * Pool that can create further elements when depleted. * * @param <T> The type of elements in this pool. */ public interface ElasticPool<T> { /** * This can be called by single thread only. * * @return pooled or new object. */ T acquire(); /** * Can be called by any thread. * * @param object Returned object. */ void release(T object); void reserve(int capacity); int minUsed(); int maxUsed(); void resetStats(); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/collection/LimitedPool.java
api/src/main/java/io/hyperfoil/api/collection/LimitedPool.java
package io.hyperfoil.api.collection; import java.util.Arrays; import java.util.function.Supplier; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * Fixed-size pool that can be accessed by single thread only. */ public class LimitedPool<T> { private static final Logger log = LogManager.getLogger(LimitedPool.class); private final Object[] elements; private final int size; private final int mask; private int index; public LimitedPool(int capacity, Supplier<T> init) { mask = (1 << 32 - Integer.numberOfLeadingZeros(capacity - 1)) - 1; elements = new Object[mask + 1]; size = capacity; for (int i = 0; i < capacity; ++i) { elements[i] = init.get(); } } public LimitedPool(T[] array) { mask = (1 << 32 - Integer.numberOfLeadingZeros(array.length - 1)) - 1; elements = new Object[mask + 1]; size = array.length; System.arraycopy(array, 0, elements, 0, array.length); } public void reset(Object[] array) { if (array.length != size) { throw new IllegalArgumentException( "Pool should be initialized with " + size + " objects (actual: " + array.length + ")"); } System.arraycopy(array, 0, elements, 0, array.length); Arrays.fill(elements, array.length, elements.length, null); } public T acquire() { int i = (index + 1) & mask; while (i != index && elements[i] == null) { i = ((i + 1) & mask); } if (elements[i] == null) { return null; } else { index = i; @SuppressWarnings("unchecked") T object = (T) elements[i]; elements[i] = null; return object; } } public void release(T object) { int i = index; int stop = (index + mask) & mask; while (i != stop && elements[i & mask] != null) ++i; if (elements[i] == null) { index = (i + mask) & mask; elements[i] = object; } else { // This should not happen... for (i = 0; i < elements.length; ++i) { if (elements[i] == object) { log.error("{} already returned to pool!", object); return; } } throw new IllegalStateException("Pool should not be full!"); } } public boolean isFull() { int currentSize = 0; for (Object o : elements) { if (o != null) { currentSize++; } } return currentSize == size; } public boolean isDepleted() { for (Object o : elements) { if (o != null) return false; } return true; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/Session.java
api/src/main/java/io/hyperfoil/api/session/Session.java
package io.hyperfoil.api.session; import java.io.Serializable; import java.util.function.Supplier; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.config.Scenario; import io.hyperfoil.api.connection.Request; import io.hyperfoil.api.statistics.SessionStatistics; import io.hyperfoil.api.statistics.Statistics; import io.netty.util.concurrent.EventExecutor; public interface Session { Runnable runTask(); void reserve(Scenario scenario); /** * @return int &gt;= 0 that's unique across whole simulation */ int uniqueId(); int agentThreadId(); int agentThreads(); int globalThreadId(); int globalThreads(); int agentId(); int agents(); String runId(); EventExecutor executor(); ThreadData threadData(); AgentData agentData(); GlobalData globalData(); PhaseInstance phase(); long phaseStartTimestamp(); Statistics statistics(int stepId, String name); void pruneStats(Phase phase); // Resources /** * See {@link #declareResource(ResourceKey, Supplier, boolean)}, with <code>singleton</code> defaulting to <code>false</code> * * @param key Unique key (usually the step or handler itself) * @param resourceSupplier Supplier creating the resource, possible multiple times. * @param <R> Resource type. */ <R extends Session.Resource> void declareResource(ResourceKey<R> key, Supplier<R> resourceSupplier); /** * Reserve space in the session for a resource, stored under given key. If this is executed within * a {@link io.hyperfoil.api.config.Sequence sequence} with non-zero * {@link io.hyperfoil.api.config.Sequence#concurrency() concurrency} the session * stores one resource for each concurrent instance. If this behaviour should be avoided set * <code>singleton</code> to true. * * @param key Unique key (usually the step or handler itself) * @param resourceSupplier Supplier creating the resource, possible multiple times. * @param singleton Is the resource shared amongst concurrent sequences? * @param <R> Resource type. */ <R extends Session.Resource> void declareResource(ResourceKey<R> key, Supplier<R> resourceSupplier, boolean singleton); <R extends Session.Resource> void declareSingletonResource(ResourceKey<R> key, R resource); <R extends Session.Resource> R getResource(ResourceKey<R> key); // Sequence related methods void currentSequence(SequenceInstance current); SequenceInstance currentSequence(); void attach(EventExecutor executor, ThreadData threadData, AgentData agentData, GlobalData globalData, SessionStatistics statistics); void start(PhaseInstance phase); /** * Run anything that can be executed. */ void proceed(); void reset(); SequenceInstance startSequence(String name, boolean forceSameIndex, ConcurrencyPolicy policy); void stop(); void fail(Throwable t); boolean isActive(); /** * @return Currently executed request, or <code>null</code> if not in scope. */ Request currentRequest(); void currentRequest(Request request); enum VarType { OBJECT, INTEGER } interface Var { boolean isSet(); void unset(); VarType type(); // While the session parameter is not necessary for regular Vars stored // inside the session it is useful for the special ones. default int intValue(Session session) { throw new UnsupportedOperationException(); } default Object objectValue(Session session) { throw new UnsupportedOperationException(); } } interface Resource { default void onSessionReset(Session session) { } default void destroy() { } } interface ResourceKey<R extends Resource> extends Serializable { } /** * Behaviour when a new sequence start is requested but the concurrency factor is exceeded. */ enum ConcurrencyPolicy { FAIL, WARN, } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/ThreadData.java
api/src/main/java/io/hyperfoil/api/session/ThreadData.java
package io.hyperfoil.api.session; import java.util.function.LongBinaryOperator; /** * Data shared among sessions bound to the same {@link Session#executor() executor thread}. */ public interface ThreadData { SharedMap newMap(String key); SharedMap pullMap(String key); SharedMap pullMap(String key, Object match, Object value); void pushMap(String key, SharedMap sharedMap); void releaseMap(String key, SharedMap map); void reserveMap(String key, Object match, int entries); SharedCounter reserveCounter(String key); SharedCounter getCounter(String key); interface SharedMap { void put(Object key, Object value); Object get(Object key); int size(); int capacity(); void clear(); } /** * Counter shared by multiple sessions. */ interface SharedCounter { /** * @return Current value. */ long get(); /** * @param value Number. * @return Previous value. */ long set(long value); /** * @param value Number. * @return Sum of previous value and the parameter. */ long apply(LongBinaryOperator operator, long value); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/AgentData.java
api/src/main/java/io/hyperfoil/api/session/AgentData.java
package io.hyperfoil.api.session; /** * Data structure that holds immutable data with push-once semantics. */ public interface AgentData { void push(Session session, String name, Object object); void pull(Session session, String name, ObjectAccess access); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/PhaseChangeHandler.java
api/src/main/java/io/hyperfoil/api/session/PhaseChangeHandler.java
package io.hyperfoil.api.session; import java.util.concurrent.CompletableFuture; import io.hyperfoil.api.config.Phase; public interface PhaseChangeHandler { CompletableFuture<Void> onChange(Phase phase, PhaseInstance.Status status, boolean sessionLimitExceeded, Throwable error); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/SessionStopException.java
api/src/main/java/io/hyperfoil/api/session/SessionStopException.java
package io.hyperfoil.api.session; /** * This exception is raised to prevent any further processing after the session is stopped. */ public class SessionStopException extends RuntimeException { public static final SessionStopException INSTANCE = new SessionStopException(); private SessionStopException() { super(null, null, false, false); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/ObjectAccess.java
api/src/main/java/io/hyperfoil/api/session/ObjectAccess.java
package io.hyperfoil.api.session; public interface ObjectAccess extends WriteAccess { void setObject(Session session, Object value); /** * Make variable set without changing its (pre-allocated) value. * * @param session Session with variables. * @return Variable value */ Object activate(Session session); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/ResourceUtilizer.java
api/src/main/java/io/hyperfoil/api/session/ResourceUtilizer.java
package io.hyperfoil.api.session; import java.util.ArrayList; import io.hyperfoil.impl.CollectingVisitor; public interface ResourceUtilizer { void reserve(Session session); static void reserveForTesting(Session session, Object o) { Visitor visitor = new Visitor(); visitor.visit(o); for (ResourceUtilizer ru : visitor.resourceUtilizers()) { ru.reserve(session); } } class Visitor extends CollectingVisitor<ResourceUtilizer> { private final ArrayList<ResourceUtilizer> resourceUtilizers = new ArrayList<>(); public Visitor() { super(ResourceUtilizer.class); } @Override protected boolean process(ResourceUtilizer value) { resourceUtilizers.add(value); return true; } public ResourceUtilizer[] resourceUtilizers() { return resourceUtilizers.toArray(new ResourceUtilizer[0]); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/Action.java
api/src/main/java/io/hyperfoil/api/session/Action.java
package io.hyperfoil.api.session; import java.io.Serializable; import io.hyperfoil.api.config.BuilderBase; /** * Actions are similar to {@link io.hyperfoil.api.config.Step steps} but are executed unconditionally; * Action cannot block sequence execution. */ public interface Action extends Serializable { void run(Session session); interface Builder extends BuilderBase<Builder> { Action build(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/IntAccess.java
api/src/main/java/io/hyperfoil/api/session/IntAccess.java
package io.hyperfoil.api.session; public interface IntAccess extends WriteAccess { void setInt(Session session, int value); int addToInt(Session session, int delta); @Override Session.Var getVar(Session session); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/WriteAccess.java
api/src/main/java/io/hyperfoil/api/session/WriteAccess.java
package io.hyperfoil.api.session; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public interface WriteAccess extends ReadAccess { Logger log = LogManager.getLogger(WriteAccess.class); boolean trace = log.isTraceEnabled(); void unset(Session session); Session.Var createVar(Session session, Session.Var existing); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/ReadAccess.java
api/src/main/java/io/hyperfoil/api/session/ReadAccess.java
package io.hyperfoil.api.session; import java.io.Serializable; public interface ReadAccess extends Serializable { boolean isSet(Session session); Object getObject(Session session); int getInt(Session session); boolean isSequenceScoped(); Session.Var getVar(Session session); Object key(); void setIndex(int index); int index(); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/ControllerListener.java
api/src/main/java/io/hyperfoil/api/session/ControllerListener.java
package io.hyperfoil.api.session; import java.util.Map; import java.util.concurrent.CompletableFuture; import io.hyperfoil.api.config.Phase; public interface ControllerListener { CompletableFuture<Void> onPhaseChange(Phase phase, PhaseInstance.Status status, boolean sessionLimitExceeded, Throwable error, Map<String, GlobalData.Element> globalData); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/GlobalData.java
api/src/main/java/io/hyperfoil/api/session/GlobalData.java
package io.hyperfoil.api.session; import java.io.Serializable; public interface GlobalData { /** * Offers an element for publishing. When the publishing phase terminates all elements with the same key * are combined together (in arbitrary order) on the controller. The resulting element is then * made available to phases started strictly after publishing phase. If there is already an existing * element with this key present all remaining phases are cancelled and an error is reported. * * @param phase * @param key Identifier. * @param element Custom element. */ void publish(String phase, String key, Element element); /** * Retrieves the element created in one of strictly preceding phases. * * @param key Identifier. * @return Custom element. */ Element read(String key); /** * This interface is typically implemented in extensions. */ interface Element extends Serializable { /** * Creates a new instance of accumulator for combining multiple elements. * * @return Empty accumulator instance. */ Accumulator newAccumulator(); } interface Accumulator { /** * Add a new element to the accumulator. The elements can be combined in arbitrary * order, extracted into another element using {@link #complete()} and combined again. * * @param e Element of the same type that created this accumulator. * @throws IllegalArgumentException if the element is of unsupported type. */ void add(Element e); /** * Transforms contents of this accumulator into a combined element. * * @return Combined element. */ Element complete(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/AccessVisitor.java
api/src/main/java/io/hyperfoil/api/session/AccessVisitor.java
package io.hyperfoil.api.session; import java.util.ArrayList; import io.hyperfoil.impl.CollectingVisitor; public class AccessVisitor extends CollectingVisitor<ReadAccess> { private final ArrayList<ReadAccess> reads = new ArrayList<>(); private final ArrayList<WriteAccess> writes = new ArrayList<>(); public AccessVisitor() { super(ReadAccess.class); } @Override protected boolean process(ReadAccess value) { reads.add(value); if (value instanceof WriteAccess) { writes.add((WriteAccess) value); } return false; } public ReadAccess[] reads() { return reads.toArray(new ReadAccess[0]); } public WriteAccess[] writes() { return writes.toArray(new WriteAccess[0]); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/SequenceInstance.java
api/src/main/java/io/hyperfoil/api/session/SequenceInstance.java
package io.hyperfoil.api.session; import java.util.function.Consumer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.FormattedMessage; import io.hyperfoil.api.config.Sequence; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.config.StepBuilder; public class SequenceInstance { private static final Logger log = LogManager.getLogger(SequenceInstance.class); private static final boolean trace = log.isTraceEnabled(); private Sequence sequence; private Consumer<SequenceInstance> releaseHandler; private int index; private Step[] steps; private int currentStep = 0; private int refCnt = 0; public boolean progress(Session session) { boolean progressed = false; while (currentStep < steps.length) { Step step = steps[currentStep]; if (trace) { log.trace("#{} {}[{}] invoking step {}", session.uniqueId(), sequence.name(), index, StepBuilder.nameOf(step)); } session.currentSequence(this); try { if (!step.invoke(session)) { if (trace) { log.trace("#{} {}[{}] step {} is blocked", session.uniqueId(), sequence.name(), index, StepBuilder.nameOf(step)); } if (currentStep >= steps.length) { log.warn("#{} Last step reported being blocked but it has also interrupted the sequence.", session.uniqueId()); } return progressed; } // If session becomes inactive it means that the originally thrown exception was not properly propagated if (!session.isActive()) { throw SessionStopException.INSTANCE; } } catch (SessionStopException e) { // just rethrow throw e; } catch (Throwable t) { log.error(new FormattedMessage("#{} phase {}, seq {}[{}] failure invoking step {}", session.uniqueId(), session.phase().definition().name(), sequence.name(), index, StepBuilder.nameOf(step)), t); session.fail(t); return false; } finally { session.currentSequence(null); } if (currentStep < steps.length) { ++currentStep; } progressed = true; } return progressed; } public SequenceInstance reset(Sequence sequence, int index, Step[] steps, Consumer<SequenceInstance> releaseHandler) { this.sequence = sequence; this.releaseHandler = releaseHandler; this.index = index; this.steps = steps; this.currentStep = 0; this.refCnt = 1; return this; } public boolean isCompleted() { return currentStep >= steps.length; } public boolean isLastStep() { return currentStep == steps.length - 1; } public int index() { return index; } public Sequence definition() { return sequence; } @Override public String toString() { return appendTo(new StringBuilder()).toString(); } public StringBuilder appendTo(StringBuilder sb) { return sb.append(sequence != null ? sequence.name() : "<none>") .append('(').append(index).append(")(") .append(currentStep + 1).append('/').append(steps == null ? 0 : steps.length).append(')'); } public void breakSequence(Session session) { this.currentStep = steps.length; if (trace) { log.trace("#{} was interrupted", session.uniqueId()); } } public void restart(Session session) { log.trace("#{} Restarting current sequence.", session.uniqueId()); // FIXME: hack - setting this to -1 causes the progress() increment to 0 and start from the beginning // Steps cannot use just reset(...) because the increment after a non-blocking step would skip the first // step in this sequence. this.currentStep = -1; } public SequenceInstance incRefCnt() { refCnt++; return this; } public void decRefCnt(Session session) { assert refCnt > 0; if (--refCnt == 0) { if (trace) { log.trace("#{} Releasing sequence {}[{}]", session.uniqueId(), sequence == null ? "<noseq>" : sequence.name(), index); } if (releaseHandler != null) { releaseHandler.accept(this); } } else if (trace) { // session is null in some mocked tests log.trace("#{} Not releasing sequence {}[{}] - refCnt {}", session == null ? 0 : session.uniqueId(), sequence == null ? "<noseq>" : sequence.name(), index, refCnt); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/session/PhaseInstance.java
api/src/main/java/io/hyperfoil/api/session/PhaseInstance.java
package io.hyperfoil.api.session; import java.util.List; import io.hyperfoil.api.collection.ElasticPool; import io.hyperfoil.api.config.Phase; import io.netty.util.concurrent.EventExecutorGroup; public interface PhaseInstance { Phase definition(); Status status(); void proceed(EventExecutorGroup executorGroup); long absoluteStartTime(); String absoluteStartTimeAsString(); void start(EventExecutorGroup executorGroup); void finish(); void tryTerminate(); void terminate(); // TODO better name void setComponents(ElasticPool<Session> sessionPool, List<Session> sessionList, PhaseChangeHandler phaseChangeHandler); void runOnFailedSessionAcquisition(Runnable action); void reserveSessions(); void notifyFinished(Session session); void setTerminated(); void fail(Throwable error); Throwable getError(); String runId(); int agentId(); int agentThreads(); int agentFirstThreadId(); void setStatsComplete(); enum Status { NOT_STARTED, RUNNING, FINISHED, TERMINATING, TERMINATED, STATS_COMPLETE; public boolean isFinished() { return this.ordinal() >= FINISHED.ordinal(); } public boolean isTerminated() { return this.ordinal() >= TERMINATED.ordinal(); } public boolean isStarted() { return this.ordinal() >= RUNNING.ordinal(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/SLABuilder.java
api/src/main/java/io/hyperfoil/api/config/SLABuilder.java
package io.hyperfoil.api.config; import java.util.ArrayList; import java.util.Collection; import java.util.concurrent.TimeUnit; import io.hyperfoil.impl.Util; /** * Defines a Service Level Agreement (SLA) - conditions that must hold for benchmark to be deemed successful. */ public class SLABuilder<P> implements BuilderBase<SLABuilder<P>> { public static final SLA[] DEFAULT = new SLA[] { new SLABuilder<>(null).build() }; private final P parent; private long window = -1; private double errorRatio = 1.01; // 101% of errors allowed private double invalidRatio = 1.01; private long meanResponseTime = Long.MAX_VALUE; private final Collection<SLA.PercentileLimit> limits = new ArrayList<>(); private double blockedRatio = 0; // do not allow blocking private SLA sla; public SLABuilder(P parent) { this.parent = parent; } public void prepareBuild() { } public SLA build() { if (sla != null) { return sla; } return sla = new SLA(window, errorRatio, invalidRatio, meanResponseTime, blockedRatio, limits); } public P endSLA() { return parent; } public SLABuilder<P> window(long window, TimeUnit timeUnit) { this.window = timeUnit.toMillis(window); return this; } /** * Period over which the stats should be collected. By default the SLA applies to stats from whole phase. * * @param window Window size with suffix ('s', 'm' or 'h') or just in milliseconds. * @return Self. */ public SLABuilder<P> window(String window) { return window(Util.parseToMillis(window), TimeUnit.MILLISECONDS); } /** * Maximum allowed ratio of errors: connection failures or resets, timeouts and internal errors. Valid values are 0.0 - 1.0 * (inclusive). * Note: 4xx and 5xx statuses are NOT considered errors for this SLA parameter. Use <code>invalidRatio</code> for that. * * @param errorRatio Ratio. * @return Self. */ public SLABuilder<P> errorRatio(double errorRatio) { this.errorRatio = errorRatio; return this; } /** * Maximum allowed ratio of requests with responses marked as invalid. Valid values are 0.0 - 1.0 (inclusive). * Note: With default settings 4xx and 5xx statuses are considered invalid. Check out * <code>ergonomics.autoRangeCheck</code> or <code>httpRequest.handler.autoRangeCheck</code> to change this. * * @param invalidRatio Ratio. * @return Self. */ public SLABuilder<P> invalidRatio(double invalidRatio) { this.invalidRatio = invalidRatio; return this; } public SLABuilder<P> meanResponseTime(long meanResponseTime, TimeUnit timeUnit) { this.meanResponseTime = timeUnit.toNanos(meanResponseTime); return this; } /** * Maximum allowed mean (average) response time. Use suffix `ns`, `us`, `ms` or `s` to specify units. * * @param meanResponseTime Mean response time. * @return Self. */ public SLABuilder<P> meanResponseTime(String meanResponseTime) { return meanResponseTime(Util.parseToNanos(meanResponseTime), TimeUnit.NANOSECONDS); } /** * Maximum allowed ratio of time spent waiting for usable connection to sum of response latencies and blocked time. * Default is 0 - client must not be blocked. Set to 1 if the client can block without limits. * * @param blockedRatio Maximum ratio. * @return Self. */ public SLABuilder<P> blockedRatio(double blockedRatio) { this.blockedRatio = blockedRatio; return this; } /** * Percentile limits. * * @return Builder. */ public LimitsBuilder limits() { return new LimitsBuilder(); } /** * Percentile limits. */ public class LimitsBuilder extends PairBuilder.OfString { /** * Use percentile (value between 0.0 and 1.0) as key and response time with unit (e.g. `ms`) in suffix as value. * * @param percentileStr Percentile (value between 0.0 and 1.0). * @param responseTime Response time threshold. */ @Override public void accept(String percentileStr, String responseTime) { double percentile = Double.parseDouble(percentileStr); if (percentile < 0 || percentile > 1) { throw new BenchmarkDefinitionException("Percentile must be between 0.0 and 1.0"); } limits.add(new SLA.PercentileLimit(percentile, Util.parseToNanos(responseTime))); } public LimitsBuilder add(double percentile, long responseTime) { limits.add(new SLA.PercentileLimit(percentile, responseTime)); return this; } public SLABuilder<P> end() { return SLABuilder.this; } } /** * Defines a list of Service Level Agreements (SLAs) - conditions that must hold for benchmark to be deemed successful. */ public static class ListBuilder<P> implements MappingListBuilder<SLABuilder<ListBuilder<P>>> { private final P parent; private final ArrayList<SLABuilder<ListBuilder<P>>> sla = new ArrayList<>(); // used only for copy() public ListBuilder() { this(null); } public ListBuilder(P parent) { this.parent = parent; } /** * One or more SLA configurations. * * @return Builder. */ @Override public SLABuilder<ListBuilder<P>> addItem() { SLABuilder<ListBuilder<P>> sb = new SLABuilder<>(this); sla.add(sb); return sb; } public P endList() { return parent; } public SLA[] build() { return sla.stream().map(SLABuilder::build).toArray(SLA[]::new); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/Agent.java
api/src/main/java/io/hyperfoil/api/config/Agent.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.api.config; import java.io.Serializable; import java.util.Collections; import java.util.Map; public class Agent implements Serializable { private static final String THREADS = "threads"; public final String name; public final String inlineConfig; public final Map<String, String> properties; public Agent(String name, String inlineConfig, Map<String, String> properties) { this.name = name; this.inlineConfig = inlineConfig; this.properties = properties == null ? Collections.emptyMap() : properties; } public int threads() { String threadsProperty = properties.get(THREADS); if (threadsProperty == null || threadsProperty.isEmpty()) { return 0; } try { return Integer.parseInt(threadsProperty); } catch (NumberFormatException e) { throw new BenchmarkDefinitionException("Cannot parse number of threads for agent " + name + ": " + threadsProperty); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/Model.java
api/src/main/java/io/hyperfoil/api/config/Model.java
package io.hyperfoil.api.config; import java.io.Serializable; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public interface Model extends Serializable { Logger log = LogManager.getLogger(Phase.class); String description(); default void validate(Phase phase) { } abstract class ClosedModel implements Model { public final int users; public final int usersPerAgent; public final int usersPerThread; public ClosedModel(int users, int usersPerAgent, int usersPerThread) { this.users = users; this.usersPerAgent = usersPerAgent; this.usersPerThread = usersPerThread; } protected String description(String suffix) { if (users > 0) { return users + " users " + suffix; } else if (usersPerAgent > 0) { return usersPerAgent + " users per agent " + suffix; } else if (usersPerThread > 0) { return usersPerThread + " users per thread " + suffix; } else { return "no users will be started"; } } } class AtOnce extends ClosedModel { public AtOnce(int users, int usersPerAgent, int usersPerThread) { super(users, usersPerAgent, usersPerThread); } @Override public void validate(Phase phase) { if (phase.duration > 0) { log.warn("Duration ({} ms) for atOnce phase {} is ignored.", phase.duration, phase.name); } } @Override public String description() { return description("at once"); } } class Always extends ClosedModel { public Always(int users, int usersPerAgent, int usersPerThread) { super(users, usersPerAgent, usersPerThread); } @Override public String description() { return description("always"); } } abstract class OpenModel implements Model { public final boolean variance; public final int maxSessions; public final SessionLimitPolicy sessionLimitPolicy; public OpenModel(boolean variance, int maxSessions, SessionLimitPolicy sessionLimitPolicy) { this.variance = variance; this.maxSessions = maxSessions; this.sessionLimitPolicy = sessionLimitPolicy; } @Override public void validate(Phase phase) { if (phase.duration < 0) { throw new BenchmarkDefinitionException("Duration was not set for phase '" + phase.name + "'"); } } } class RampRate extends OpenModel { public final double initialUsersPerSec; public final double targetUsersPerSec; public RampRate(double initialUsersPerSec, double targetUsersPerSec, boolean variance, int maxSessions, SessionLimitPolicy sessionLimitPolicy) { super(variance, maxSessions, sessionLimitPolicy); this.initialUsersPerSec = initialUsersPerSec; this.targetUsersPerSec = targetUsersPerSec; } @Override public String description() { return String.format("%.2f - %.2f users per second", initialUsersPerSec, targetUsersPerSec); } } class ConstantRate extends OpenModel { public final double usersPerSec; public ConstantRate(double usersPerSec, boolean variance, int maxSessions, SessionLimitPolicy sessionLimitPolicy) { super(variance, maxSessions, sessionLimitPolicy); this.usersPerSec = usersPerSec; } @Override public String description() { return String.format("%.2f users per second", usersPerSec); } } class Sequentially implements Model { public final int repeats; public Sequentially(int repeats) { this.repeats = repeats; } @Override public String description() { return repeats + " times"; } } class Noop implements Model { @Override public String description() { return "No-op phase"; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/SLA.java
api/src/main/java/io/hyperfoil/api/config/SLA.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.api.config; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import io.hyperfoil.api.statistics.StatisticsSnapshot; public class SLA implements Serializable { private final long window; private final double errorRatio; private final double invalidRatio; private final long meanResponseTime; private final double blockedRatio; private final Collection<PercentileLimit> limits; public SLA(long window, double errorRatio, double invalidRatio, long meanResponseTime, double blockedRatio, Collection<PercentileLimit> limits) { this.window = window; this.meanResponseTime = meanResponseTime; this.errorRatio = errorRatio; this.invalidRatio = invalidRatio; this.blockedRatio = blockedRatio; this.limits = limits; } public long window() { return window; } public double errorRatio() { return errorRatio; } public double invalidRatio() { return invalidRatio; } public long meanResponseTime() { return meanResponseTime; } public double blockedRatio() { return blockedRatio; } public Collection<PercentileLimit> percentileLimits() { return Collections.unmodifiableCollection(limits); } public SLA.Failure validate(String phase, String metric, StatisticsSnapshot statistics) { double actualErrorRatio = (double) statistics.errors() / statistics.requestCount; if (statistics.errors() > 0 && actualErrorRatio >= errorRatio) { return new SLA.Failure(this, phase, metric, statistics.clone(), String.format("Error ratio exceeded: required %.3f, actual %.3f", errorRatio, actualErrorRatio)); } // Note: when a handler throws an exception the request is marked as invalid. // However the response is not recorded (because we might not be finished reading the response). // Therefore we rather compute the ration from requests to make sure invalid <= all. double actualInvalidRatio = statistics.responseCount == 0 ? 0 : (double) statistics.invalid / statistics.requestCount; if (statistics.invalid > 0 && actualInvalidRatio >= invalidRatio) { return new SLA.Failure(this, phase, metric, statistics.clone(), String.format("Invalid response ratio exceeded: required %.3f, actual %.3f", invalidRatio, actualInvalidRatio)); } if (meanResponseTime < Long.MAX_VALUE) { double mean = statistics.histogram.getMean(); if (mean >= meanResponseTime) { return new SLA.Failure(this, phase, metric, statistics.clone(), String.format("Mean response time exceeded: required %d, actual %.3f", meanResponseTime, mean)); } } if (statistics.blockedTime > 0) { double actualBlockedRatio = statistics.blockedTime / (statistics.blockedTime + statistics.histogram.getMean() * statistics.histogram.getTotalCount()); if (actualBlockedRatio > blockedRatio) { return new SLA.Failure(this, phase, metric, statistics.clone(), String.format("Progress was blocked waiting for a free connection. Hint: increase http.sharedConnections.")); } } for (SLA.PercentileLimit limit : limits) { long value = statistics.histogram.getValueAtPercentile(limit.percentile()); if (value >= limit.responseTime()) { return new SLA.Failure(this, phase, metric, statistics.clone(), String.format("Response time at percentile %f exceeded: required %d, actual %d", limit.percentile, limit.responseTime, value)); } } return null; } public static class PercentileLimit implements Serializable { private final double percentile; private final long responseTime; public PercentileLimit(double percentile, long responseTime) { this.percentile = percentile; this.responseTime = responseTime; } public double percentile() { return percentile; } /** * @return Maximum allowed response time for given percentile, in nanoseconds. */ public long responseTime() { return responseTime; } } public static class Failure { private final SLA sla; private final String phase; private final String metric; private final StatisticsSnapshot statistics; private final String message; public Failure(SLA sla, String phase, String metric, StatisticsSnapshot statistics, String message) { this.sla = sla; this.phase = phase; this.metric = metric; this.statistics = statistics; this.message = message; } public SLA sla() { return sla; } public String phase() { return phase; } public String metric() { return metric; } public StatisticsSnapshot statistics() { return statistics; } public String message() { return message; } } public interface Provider extends Step { /** * @return Step ID that will allow us to match against the SLA. */ int id(); SLA[] sla(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/Step.java
api/src/main/java/io/hyperfoil/api/config/Step.java
package io.hyperfoil.api.config; import java.io.Serializable; import io.hyperfoil.api.session.Session; public interface Step extends Serializable { /** * This method should have no side-effect if it returns false. * * @param session User session. * @return True if the step was successfully invoked or false when the execution is blocked. */ boolean invoke(Session session); /** * Marker interface that should have single implementation in other module. */ interface Catalog { } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/BenchmarkDefinitionException.java
api/src/main/java/io/hyperfoil/api/config/BenchmarkDefinitionException.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.api.config; public class BenchmarkDefinitionException extends RuntimeException { public BenchmarkDefinitionException(String msg) { super(getMessage(msg)); } public BenchmarkDefinitionException(String msg, Throwable cause) { super(getMessage(msg), cause); } private static String getMessage(String msg) { if (Locator.isAvailable()) { return Locator.current().locationMessage() + ": " + msg; } else { return msg; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/IncludeBuilders.java
api/src/main/java/io/hyperfoil/api/config/IncludeBuilders.java
package io.hyperfoil.api.config; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.util.function.Function; /** * Mark this (abstract builder) interface with this annotation to include covariant builders. */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface IncludeBuilders { Conversion[] value(); @interface Conversion { /** * @return Builder class that should be loaded in addition to the one the {@link IncludeBuilders} * annotation is attached to. */ Class<?> from(); /** * @return Class implementing function that adapts builder loaded through {@link #from()} * to builder of type where {@link IncludeBuilders} is attached. */ Class<? extends Function<?, ?>> adapter(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/Locator.java
api/src/main/java/io/hyperfoil/api/config/Locator.java
package io.hyperfoil.api.config; import java.util.Stack; public interface Locator { StepBuilder<?> step(); BaseSequenceBuilder<?> sequence(); ScenarioBuilder scenario(); BenchmarkBuilder benchmark(); String locationMessage(); static Locator current() { Stack<Locator> stack = Holder.CURRENT.get(); if (stack.isEmpty()) { throw new IllegalArgumentException( "Locator is not set. This method must be invoked within the prepareBuild() or build() phase of scenario."); } return stack.peek(); } static boolean isAvailable() { Stack<Locator> stack = Holder.CURRENT.get(); return !stack.isEmpty(); } static void push(Locator locator) { Holder.CURRENT.get().push(locator); } static void push(StepBuilder<?> stepBuilder, BaseSequenceBuilder<?> sequenceBuilder) { Stack<Locator> stack = Holder.CURRENT.get(); stack.push(new Impl(stepBuilder, sequenceBuilder, sequenceBuilder.endSequence())); } static void push(ScenarioBuilder scenarioBuilder) { Stack<Locator> stack = Holder.CURRENT.get(); stack.push(new Impl(null, null, scenarioBuilder)); } static void pop() { Holder.CURRENT.get().pop(); } class Holder { private static final ThreadLocal<Stack<Locator>> CURRENT = ThreadLocal.withInitial(Stack::new); } class Impl implements Locator { private final StepBuilder<?> step; private final BaseSequenceBuilder<?> sequence; private final ScenarioBuilder scenario; private Impl(StepBuilder<?> step, BaseSequenceBuilder<?> sequence, ScenarioBuilder scenario) { this.step = step; this.sequence = sequence; this.scenario = scenario; } public StepBuilder<?> step() { return step; } public BaseSequenceBuilder<?> sequence() { return sequence; } public ScenarioBuilder scenario() { return scenario; } @Override public BenchmarkBuilder benchmark() { return scenario().endScenario().endPhase(); } @Override public String locationMessage() { StringBuilder sb = new StringBuilder("Phase ").append(scenario().endScenario().name); String forkName = scenario().fork().name; if (forkName != null) { sb.append("/").append(forkName); } if (sequence != null) { sb.append(", sequence ").append(sequence.name()); } if (step != null) { sb.append(", step "); sb.append(StepBuilder.nameOf(step)); int stepIndex = sequence.indexOf(step); if (stepIndex >= 0) { sb.append(" (").append(stepIndex).append("/").append(sequence.size()).append(")"); } } return sb.toString(); } } abstract class Abstract implements Locator { @Override public StepBuilder<?> step() { throw new UnsupportedOperationException(); } @Override public BaseSequenceBuilder<?> sequence() { throw new UnsupportedOperationException(); } @Override public ScenarioBuilder scenario() { throw new UnsupportedOperationException(); } @Override public BenchmarkBuilder benchmark() { throw new UnsupportedOperationException(); } @Override public String locationMessage() { return ""; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/MappingListBuilder.java
api/src/main/java/io/hyperfoil/api/config/MappingListBuilder.java
package io.hyperfoil.api.config; public interface MappingListBuilder<B> { B addItem(); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/PluginConfig.java
api/src/main/java/io/hyperfoil/api/config/PluginConfig.java
package io.hyperfoil.api.config; import java.io.Serializable; public interface PluginConfig extends Serializable { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/Sequence.java
api/src/main/java/io/hyperfoil/api/config/Sequence.java
package io.hyperfoil.api.config; import java.io.Serializable; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.Session; /** * Sequences are a series of one or more {@link Step}'s that perform one logical unit of operation. Steps within a Sequence are * executed in order. * State is shared between sequences via the {@link Session}. This allows sequences to pass request scoped state between * {@link Step} invocations. * <p> * Sequences form the basis of a timed operation. */ public class Sequence implements Serializable { private final String name; private final int id; private final int concurrency; private final int offset; private final Step[] steps; private final ResourceUtilizer[] resourceUtilizers; public Sequence(String name, int id, int concurrency, int offset, Step[] steps) { this.name = name; this.id = id; this.concurrency = concurrency; this.offset = offset; this.steps = steps; ResourceUtilizer.Visitor visitor = new ResourceUtilizer.Visitor(); visitor.visit(this.steps); this.resourceUtilizers = visitor.resourceUtilizers(); } public int id() { return id; } public int concurrency() { return concurrency; } /** * @return Index for first instance for cases where we need an array of all concurrent instances. */ public int offset() { return offset; } public void reserve(Session session) { for (ResourceUtilizer ru : resourceUtilizers) { ru.reserve(session); } } public String name() { return name; } public Step[] steps() { return steps; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/PhaseBuilder.java
api/src/main/java/io/hyperfoil/api/config/PhaseBuilder.java
package io.hyperfoil.api.config; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.function.Predicate; import java.util.stream.Collector; import java.util.stream.Collectors; import java.util.stream.IntStream; import io.hyperfoil.function.SerializableSupplier; /** * The builder creates a matrix of phases (not just single phase); we allow multiple iterations of a phase * (with increasing number of users) and multiple forks (different scenarios, but same configuration). */ public abstract class PhaseBuilder<PB extends PhaseBuilder<PB>> { protected final String name; protected final BenchmarkBuilder parent; protected long startTime = -1; protected Collection<PhaseReference> startAfter = new ArrayList<>(); protected Collection<PhaseReference> startAfterStrict = new ArrayList<>(); protected Collection<PhaseReference> terminateAfterStrict = new ArrayList<>(); protected long duration = -1; protected long maxDuration = -1; protected int maxIterations = 1; protected boolean forceIterations = false; protected List<PhaseForkBuilder> forks = new ArrayList<>(); protected boolean isWarmup = false; protected Map<String, List<SLABuilder<PB>>> customSlas = new HashMap<>(); protected PhaseReferenceDelay startWith; protected PhaseBuilder(BenchmarkBuilder parent, String name) { this.name = name; this.parent = parent; parent.addPhase(name, this); } public static Phase noop(SerializableSupplier<Benchmark> benchmark, int id, int iteration, String iterationName, long duration, Collection<String> startAfter, Collection<String> startAfterStrict, Collection<String> terminateAfterStrict) { Scenario scenario = new Scenario(new Sequence[0], new Sequence[0], 0, 0); return new Phase(benchmark, id, iteration, iterationName, scenario, -1, startAfter, startAfterStrict, terminateAfterStrict, duration, duration, null, true, new Model.Noop(), Collections.emptyMap(), null); } public BenchmarkBuilder endPhase() { return parent; } public String name() { return name; } public ScenarioBuilder scenario() { if (forks.isEmpty()) { PhaseForkBuilder fork = new PhaseForkBuilder(this, null); forks.add(fork); return fork.scenario; } else if (forks.size() == 1 && forks.get(0).name == null) { throw new BenchmarkDefinitionException("Scenario for " + name + " already set!"); } else { throw new BenchmarkDefinitionException("Scenario is forked; you need to specify another fork."); } } @SuppressWarnings("unchecked") protected PB self() { return (PB) this; } public PhaseForkBuilder fork(String name) { if (forks.size() == 1 && forks.get(0).name == null) { throw new BenchmarkDefinitionException("Scenario for " + name + " already set!"); } else { PhaseForkBuilder fork = new PhaseForkBuilder(this, name); forks.add(fork); return fork; } } public PB startTime(long startTime) { this.startTime = startTime; return self(); } public PB startAfter(String phase) { this.startAfter.add(new PhaseReference(phase, RelativeIteration.NONE, null)); return self(); } public PB startAfter(PhaseReference phase) { this.startAfter.add(phase); return self(); } public PB startAfterStrict(String phase) { this.startAfterStrict.add(new PhaseReference(phase, RelativeIteration.NONE, null)); return self(); } public PB startAfterStrict(PhaseReference phase) { this.startAfterStrict.add(phase); return self(); } public PB startWith(String phase) { if (this.startWith != null) { throw new BenchmarkDefinitionException( "Start with " + this.startWith.phase + " already defined, cannot set multiple startWith clauses"); } this.startWith = new PhaseReferenceDelay(phase, RelativeIteration.NONE, null, 0); return self(); } public PB startWith(PhaseReferenceDelay startWith) { if (this.startWith != null) { throw new BenchmarkDefinitionException( "Start with " + this.startWith.phase + " already defined, cannot set multiple startWith clauses"); } this.startWith = startWith; return self(); } public PB duration(long duration) { this.duration = duration; return self(); } public PB maxDuration(long maxDuration) { this.maxDuration = maxDuration; return self(); } public PB maxIterations(int iterations) { this.maxIterations = iterations; return self(); } public void prepareBuild() { forks.forEach(fork -> fork.scenario.prepareBuild()); } public Collection<Phase> build(SerializableSupplier<Benchmark> benchmark, AtomicInteger idCounter) { // normalize fork weights first if (forks.isEmpty()) { throw new BenchmarkDefinitionException("Scenario for " + name + " is not defined."); } else if (forks.size() == 1 && forks.get(0).name != null) { throw new BenchmarkDefinitionException(name + " has single fork: define scenario directly."); } boolean hasForks = forks.size() > 1; forks.removeIf(fork -> fork.weight <= 0); if (forks.isEmpty()) { throw new BenchmarkDefinitionException("Phase " + name + " does not have any forks with positive weight."); } double sumWeight = forks.stream().mapToDouble(f -> f.weight).sum(); forks.forEach(f -> f.weight /= sumWeight); // create matrix of iteration|fork phases List<Phase> phases = IntStream.range(0, maxIterations) .mapToObj(iteration -> forks.stream().map(f -> buildPhase(benchmark, idCounter.getAndIncrement(), iteration, f))) .flatMap(Function.identity()).collect(Collectors.toList()); if (maxIterations > 1 || forceIterations) { if (hasForks) { // add phase covering forks in each iteration IntStream.range(0, maxIterations).mapToObj(iteration -> { String iterationName = formatIteration(name, iteration); List<String> forks = this.forks.stream().map(f -> iterationName + "/" + f.name).collect(Collectors.toList()); return noop(benchmark, idCounter.getAndIncrement(), iteration, iterationName, 0, forks, Collections.emptyList(), forks); }).forEach(phases::add); } // Referencing phase with iterations with RelativeIteration.NONE means that it starts after all its iterations List<String> lastIteration = Collections.singletonList(formatIteration(name, maxIterations - 1)); phases.add( noop(benchmark, idCounter.getAndIncrement(), 0, name, 0, lastIteration, Collections.emptyList(), lastIteration)); } else if (hasForks) { // add phase covering forks List<String> forks = this.forks.stream().map(f -> name + "/" + f.name).collect(Collectors.toList()); phases.add(noop(benchmark, idCounter.getAndIncrement(), 0, name, 0, forks, Collections.emptyList(), forks)); } return phases; } protected Phase buildPhase(SerializableSupplier<Benchmark> benchmark, int phaseId, int iteration, PhaseForkBuilder f) { Collector<Map.Entry<String, List<SLABuilder<PB>>>, ?, Map<String, SLA[]>> customSlaCollector = Collectors .toMap(Map.Entry::getKey, entry -> entry.getValue().stream().map(SLABuilder::build).toArray(SLA[]::new)); return new Phase(benchmark, phaseId, iteration, iterationName(iteration, f.name), f.scenario.build(), iterationStartTime(iteration), iterationReferences(startAfter, iteration, false), iterationReferences(startAfterStrict, iteration, true), iterationReferences(terminateAfterStrict, iteration, false), duration, maxDuration, sharedResources(f), isWarmup, createModel(iteration, f.weight), Collections.unmodifiableMap(customSlas.entrySet().stream().collect(customSlaCollector)), iterationStartWith(startWith, iteration)); } String iterationName(int iteration, String forkName) { if (maxIterations == 1 && !forceIterations) { assert iteration == 0; if (forkName == null) { return name; } else { return name + "/" + forkName; } } else { String iterationName = formatIteration(name, iteration); if (forkName == null) { return iterationName; } else { return iterationName + "/" + forkName; } } } String formatIteration(String name, int iteration) { return String.format("%s/%03d", name, iteration); } long iterationStartTime(int iteration) { return iteration == 0 ? startTime : -1; } // Identifier for phase + fork, omitting iteration String sharedResources(PhaseForkBuilder fork) { if (fork == null || fork.name == null) { return name; } else { return name + "/" + fork.name; } } Collection<String> iterationReferences(Collection<PhaseReference> refs, int iteration, boolean addSelfPrevious) { Collection<String> names = new ArrayList<>(); for (PhaseReference ref : refs) { if (ref.iteration != RelativeIteration.NONE && maxIterations <= 1 && !forceIterations) { String msg = "Phase " + name + " tries to reference " + ref.phase + "/" + ref.iteration + (ref.fork == null ? "" : "/" + ref.fork) + " but this phase does not have any iterations (cannot determine relative iteration)."; throw new BenchmarkDefinitionException(msg); } switch (ref.iteration) { case NONE: names.add(ref.phase); break; case PREVIOUS: if (iteration > 0) { names.add(formatIteration(ref.phase, iteration - 1)); } break; case SAME: names.add(formatIteration(ref.phase, iteration)); break; default: throw new IllegalArgumentException(); } } if (addSelfPrevious && iteration > 0) { names.add(formatIteration(name, iteration - 1)); } return names; } StartWithDelay iterationStartWith(PhaseReferenceDelay startWith, int iteration) { if (startWith == null) { return null; } if (startWith.iteration != RelativeIteration.NONE && maxIterations <= 1 && !forceIterations) { String msg = "Phase " + name + " tries to reference " + startWith.phase + "/" + startWith.iteration + " but this phase does not have any iterations (cannot determine relative iteration)."; throw new BenchmarkDefinitionException(msg); } String phase = null; switch (startWith.iteration) { case NONE: phase = startWith.phase; break; case PREVIOUS: if (iteration > 0) { phase = formatIteration(startWith.phase, iteration - 1); } break; case SAME: phase = formatIteration(startWith.phase, iteration - 1); break; default: throw new IllegalArgumentException(); } return phase != null ? new StartWithDelay(phase, startWith.delay) : null; } public void readForksFrom(PhaseBuilder<?> other) { for (PhaseForkBuilder builder : other.forks) { fork(builder.name).readFrom(builder); } } public void readCustomSlaFrom(PhaseBuilder<?> other) { for (var entry : other.customSlas.entrySet()) { customSlas.put(entry.getKey(), entry.getValue().stream().map(b -> { @SuppressWarnings("unchecked") SLABuilder<PB> copy = (SLABuilder<PB>) b.copy(PhaseBuilder.this); return copy; }).collect(Collectors.toList())); } } public PB forceIterations(boolean force) { this.forceIterations = force; return self(); } public PB isWarmup(boolean isWarmup) { this.isWarmup = isWarmup; return self(); } public SLABuilder<PB> customSla(String metric) { List<SLABuilder<PB>> list = this.customSlas.computeIfAbsent(metric, m -> new ArrayList<>()); SLABuilder<PB> builder = new SLABuilder<>(self()); list.add(builder); return builder; } protected abstract Model createModel(int iteration, double weight); public static class Noop extends PhaseBuilder<Noop> { protected Noop(BenchmarkBuilder parent, String name) { super(parent, name); } @Override public Collection<Phase> build(SerializableSupplier<Benchmark> benchmark, AtomicInteger idCounter) { List<Phase> phases = IntStream.range(0, maxIterations) .mapToObj(iteration -> PhaseBuilder.noop(benchmark, idCounter.getAndIncrement(), iteration, iterationName(iteration, null), duration, iterationReferences(startAfter, iteration, false), iterationReferences(startAfterStrict, iteration, true), iterationReferences(terminateAfterStrict, iteration, false))) .collect(Collectors.toList()); if (maxIterations > 1 || forceIterations) { // Referencing phase with iterations with RelativeIteration.NONE means that it starts after all its iterations List<String> lastIteration = Collections.singletonList(formatIteration(name, maxIterations - 1)); phases.add(noop(benchmark, idCounter.getAndIncrement(), 0, name, duration, lastIteration, Collections.emptyList(), lastIteration)); } return phases; } @Override protected Model createModel(int iteration, double weight) { throw new UnsupportedOperationException(); } } public abstract static class ClosedModel<T extends ClosedModel<T>> extends PhaseBuilder<T> { protected int users; protected int usersIncrement; protected int usersPerAgent; protected int usersPerThread; protected ClosedModel(BenchmarkBuilder parent, String name, int users) { super(parent, name); this.users = users; } public T users(int users) { this.users = users; return self(); } public T users(int base, int increment) { this.users = base; this.usersIncrement = increment; return self(); } public T usersPerAgent(int usersPerAgent) { this.usersPerAgent = usersPerAgent; return self(); } public T usersPerThread(int usersPerThread) { this.usersPerThread = usersPerThread; return self(); } protected void validate() { long propsSet = IntStream.of(users, usersPerAgent, usersPerThread).filter(u -> u > 0).count(); if (propsSet < 1) { throw new BenchmarkDefinitionException( "Phase " + name + ".users (or .usersPerAgent/.usersPerThread) must be positive."); } else if (propsSet > 1) { throw new BenchmarkDefinitionException( "Phase " + name + ": you can set only one of .users, .usersPerAgent and .usersPerThread"); } } } public static class AtOnce extends ClosedModel<AtOnce> { AtOnce(BenchmarkBuilder parent, String name, int users) { super(parent, name, users); } @Override protected Model createModel(int iteration, double weight) { validate(); return new Model.AtOnce((int) Math.round((users + usersIncrement * iteration) * weight), (int) Math.round(usersPerAgent * weight), (int) Math.round(usersPerThread * weight)); } } public static class Always extends ClosedModel<Always> { Always(BenchmarkBuilder parent, String name, int users) { super(parent, name, users); } @Override protected Model createModel(int iteration, double weight) { validate(); return new Model.Always((int) Math.round((this.users + usersIncrement * iteration) * weight), (int) Math.round(this.usersPerAgent * weight), (int) Math.round(this.usersPerThread * weight)); } } public abstract static class OpenModel<P extends PhaseBuilder<P>> extends PhaseBuilder<P> { protected int maxSessions; protected boolean variance = true; protected SessionLimitPolicy sessionLimitPolicy = SessionLimitPolicy.FAIL; protected OpenModel(BenchmarkBuilder parent, String name) { super(parent, name); } @SuppressWarnings("unchecked") public P maxSessions(int maxSessions) { this.maxSessions = maxSessions; return (P) this; } @SuppressWarnings("unchecked") public P variance(boolean variance) { this.variance = variance; return (P) this; } @SuppressWarnings("unchecked") public P sessionLimitPolicy(SessionLimitPolicy sessionLimitPolicy) { this.sessionLimitPolicy = sessionLimitPolicy; return (P) this; } } public static class RampRate extends OpenModel<RampRate> { private double initialUsersPerSec; private double initialUsersPerSecIncrement; private double targetUsersPerSec; private double targetUsersPerSecIncrement; private Predicate<Model.RampRate> constraint; private String constraintMessage; RampRate(BenchmarkBuilder parent, String name, double initialUsersPerSec, double targetUsersPerSec) { super(parent, name); this.initialUsersPerSec = initialUsersPerSec; this.targetUsersPerSec = targetUsersPerSec; } @Override protected Model createModel(int iteration, double weight) { int maxSessions; if (this.maxSessions > 0) { maxSessions = (int) Math.round(this.maxSessions * weight); } else { double maxInitialUsers = initialUsersPerSec + initialUsersPerSecIncrement * (maxIterations - 1); double maxTargetUsers = targetUsersPerSec + targetUsersPerSecIncrement * (maxIterations - 1); maxSessions = (int) Math.ceil(Math.max(maxInitialUsers, maxTargetUsers) * weight); } if (initialUsersPerSec < 0) { throw new BenchmarkDefinitionException("Phase " + name + ".initialUsersPerSec must be non-negative"); } if (targetUsersPerSec < 0) { throw new BenchmarkDefinitionException("Phase " + name + ".targetUsersPerSec must be non-negative"); } if (initialUsersPerSec < 0.0001 && targetUsersPerSec < 0.0001) { throw new BenchmarkDefinitionException("In phase " + name + " both initialUsersPerSec and targetUsersPerSec are 0"); } double initial = (this.initialUsersPerSec + initialUsersPerSecIncrement * iteration) * weight; double target = (this.targetUsersPerSec + targetUsersPerSecIncrement * iteration) * weight; Model.RampRate model = new Model.RampRate(initial, target, variance, maxSessions, sessionLimitPolicy); if (constraint != null && !constraint.test(model)) { throw new BenchmarkDefinitionException("Phase " + name + " failed constraints: " + constraintMessage); } return model; } public RampRate initialUsersPerSec(double initialUsersPerSec) { this.initialUsersPerSec = initialUsersPerSec; this.initialUsersPerSecIncrement = 0; return this; } public RampRate initialUsersPerSec(double base, double increment) { this.initialUsersPerSec = base; this.initialUsersPerSecIncrement = increment; return this; } public RampRate targetUsersPerSec(double targetUsersPerSec) { this.targetUsersPerSec = targetUsersPerSec; this.targetUsersPerSecIncrement = 0; return this; } public RampRate targetUsersPerSec(double base, double increment) { this.targetUsersPerSec = base; this.targetUsersPerSecIncrement = increment; return this; } public RampRate constraint(Predicate<Model.RampRate> constraint, String constraintMessage) { this.constraint = constraint; this.constraintMessage = constraintMessage; return this; } } public static class ConstantRate extends OpenModel<ConstantRate> { private double usersPerSec; private double usersPerSecIncrement; ConstantRate(BenchmarkBuilder parent, String name, double usersPerSec) { super(parent, name); this.usersPerSec = usersPerSec; } @Override protected Model createModel(int iteration, double weight) { int maxSessions; if (this.maxSessions <= 0) { maxSessions = (int) Math.ceil(weight * (usersPerSec + usersPerSecIncrement * (maxIterations - 1))); } else { maxSessions = (int) Math.round(this.maxSessions * weight); } if (usersPerSec <= 0) { throw new BenchmarkDefinitionException("Phase " + name + ".usersPerSec must be positive."); } double rate = (this.usersPerSec + usersPerSecIncrement * iteration) * weight; return new Model.ConstantRate(rate, variance, maxSessions, sessionLimitPolicy); } public ConstantRate usersPerSec(double usersPerSec) { this.usersPerSec = usersPerSec; return this; } public ConstantRate usersPerSec(double base, double increment) { this.usersPerSec = base; this.usersPerSecIncrement = increment; return this; } } public static class Sequentially extends PhaseBuilder<Sequentially> { private int repeats; protected Sequentially(BenchmarkBuilder parent, String name, int repeats) { super(parent, name); this.repeats = repeats; } @Override protected Model createModel(int iteration, double weight) { if (repeats <= 0) { throw new BenchmarkDefinitionException("Phase " + name + ".repeats must be positive"); } return new Model.Sequentially(repeats); } } public static class Catalog { private final BenchmarkBuilder parent; private final String name; Catalog(BenchmarkBuilder parent, String name) { this.parent = parent; this.name = name; } public Noop noop() { return new PhaseBuilder.Noop(parent, name); } public AtOnce atOnce(int users) { return new PhaseBuilder.AtOnce(parent, name, users); } public Always always(int users) { return new PhaseBuilder.Always(parent, name, users); } public RampRate rampRate(int initialUsersPerSec, int targetUsersPerSec) { return new RampRate(parent, name, initialUsersPerSec, targetUsersPerSec); } public ConstantRate constantRate(int usersPerSec) { return new ConstantRate(parent, name, usersPerSec); } public Sequentially sequentially(int repeats) { return new Sequentially(parent, name, repeats); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/InitFromParam.java
api/src/main/java/io/hyperfoil/api/config/InitFromParam.java
package io.hyperfoil.api.config; /** * Allow to set up the builder from single string param. */ public interface InitFromParam<S extends InitFromParam<S>> { S init(String param); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/RunHook.java
api/src/main/java/io/hyperfoil/api/config/RunHook.java
package io.hyperfoil.api.config; import java.io.Serializable; import java.util.Map; import java.util.Objects; import java.util.function.Consumer; public abstract class RunHook implements Serializable, Comparable<RunHook> { protected final String name; protected RunHook(String name) { this.name = Objects.requireNonNull(name); } public String name() { return name; } public abstract boolean run(Map<String, String> properties, Consumer<String> outputConsumer); @Override public int compareTo(RunHook other) { return name.compareTo(other.name); } public interface Builder { RunHook build(String name); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/Embed.java
api/src/main/java/io/hyperfoil/api/config/Embed.java
package io.hyperfoil.api.config; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * For purposes of configuration embed all properties into the declaring builder. * <p> * If this annotation is used on a method it must be a public non-static no-arg method. * If this annotation is used on a field it must be a public final field. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.FIELD, ElementType.METHOD }) public @interface Embed { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/SequenceBuilder.java
api/src/main/java/io/hyperfoil/api/config/SequenceBuilder.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.api.config; import io.hyperfoil.api.session.Session; /** * @author <a href="mailto:stalep@gmail.com">Ståle Pedersen</a> */ public class SequenceBuilder extends BaseSequenceBuilder<SequenceBuilder> { @IgnoreCopy private final ScenarioBuilder scenario; private String name; private int id; // Concurrency 0 means single instance (not allowing access to sequence-scoped vars) // while 1 would be a special case of concurrent instances with only one allowed. private int concurrency = 0; private Sequence sequence; // Next sequence as set by parser. It's not possible to add this as nextSequence step // since that would break anchors - we can insert it only after parsing is complete. private String nextSequence; // this method is public for copy() public SequenceBuilder(ScenarioBuilder scenario) { super(null); this.scenario = scenario; } SequenceBuilder name(String name) { int concurrencyIndex = name.indexOf('['); this.name = concurrencyIndex < 0 ? name : name.substring(0, concurrencyIndex).trim(); if (concurrencyIndex >= 0) { if (!name.endsWith("]")) { throw new BenchmarkDefinitionException("Malformed sequence name with concurrency: " + name); } try { this.concurrency = Integer.parseInt(name.substring(concurrencyIndex + 1, name.length() - 1)); } catch (NumberFormatException e) { throw new BenchmarkDefinitionException("Malformed sequence name with concurrency: " + name); } } return this; } public SequenceBuilder concurrency(int concurrency) { this.concurrency = concurrency; return this; } public int concurrency() { return concurrency; } @Override public void prepareBuild() { // capture local var to prevent SequenceBuilder serialization String nextSequence = this.nextSequence; if (nextSequence != null) { step(new NextSequenceStep(nextSequence)); } super.prepareBuild(); } public Sequence build(int offset) { if (sequence != null) { return sequence; } sequence = new Sequence(this.name, id, this.concurrency, offset, buildSteps().toArray(new Step[0])); return sequence; } void id(int id) { this.id = id; } @Override public SequenceBuilder rootSequence() { return this; } public ScenarioBuilder endSequence() { return scenario; } public String name() { return name; } public void nextSequence(String nextSequence) { this.nextSequence = nextSequence; } private static class NextSequenceStep implements Step { private final String sequence; NextSequenceStep(String sequence) { this.sequence = sequence; } @Override public boolean invoke(Session s) { s.startSequence(sequence, false, Session.ConcurrencyPolicy.FAIL); return true; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/StepBuilder.java
api/src/main/java/io/hyperfoil/api/config/StepBuilder.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.api.config; import java.util.Collections; import java.util.List; import java.util.function.Function; import io.hyperfoil.api.session.Action; import io.hyperfoil.api.session.Session; /** * @author <a href="mailto:stalep@gmail.com">Ståle Pedersen</a> */ @IncludeBuilders(@IncludeBuilders.Conversion(from = Action.Builder.class, adapter = StepBuilder.ActionBuilderConverter.class)) public interface StepBuilder<S extends StepBuilder<S>> extends BuilderBase<S> { static String nameOf(StepBuilder<?> builder) { Class<?> builderClass = builder.getClass(); if (builder instanceof ActionAdapter) { builderClass = ((ActionAdapter) builder).builder.getClass(); } Name nameAnnotation = builderClass.getAnnotation(Name.class); if (nameAnnotation != null) { return nameAnnotation.value(); } else { if ("Builder".equals(builderClass.getSimpleName()) && builderClass.getEnclosingClass() != null) { return simpleName(builderClass.getEnclosingClass()); } else { return simpleName(builderClass); } } } static String nameOf(Step step) { if (step == null) { return null; } Object instance = step; if (step instanceof ActionStep) { instance = ((ActionStep) step).action; } Class<?> instanceClass = instance.getClass(); for (Class<?> maybeBuilder : instanceClass.getClasses()) { if ("Builder".equals(maybeBuilder.getSimpleName()) && maybeBuilder.isAnnotationPresent(Name.class)) { return maybeBuilder.getAnnotation(Name.class).value(); } } return simpleName(instanceClass); } private static String simpleName(Class<?> builderClass) { String name = builderClass.getSimpleName(); name = Character.toLowerCase(name.charAt(0)) + name.substring(1); if (name.endsWith("Step")) { return name.substring(0, name.length() - 4); } else if (name.endsWith("Action")) { return name.substring(0, name.length() - 6); } else { return name; } } List<Step> build(); default int id() { return -1; } class ActionBuilderConverter implements Function<Action.Builder, StepBuilder> { @Override public StepBuilder apply(Action.Builder builder) { return new ActionAdapter(builder); } } class ActionAdapter implements StepBuilder<ActionAdapter> { final Action.Builder builder; public ActionAdapter(Action.Builder builder) { this.builder = builder; } @Override public void prepareBuild() { builder.prepareBuild(); } @Override public ActionAdapter copy(Object newParent) { return new ActionAdapter(builder.copy(null)); } @Override public List<Step> build() { return Collections.singletonList(new ActionStep(builder.build())); } } class ActionStep implements Step { private final Action action; public ActionStep(Action action) { this.action = action; } @Override public boolean invoke(Session session) { action.run(session); return true; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/PhaseReferenceDelay.java
api/src/main/java/io/hyperfoil/api/config/PhaseReferenceDelay.java
package io.hyperfoil.api.config; public class PhaseReferenceDelay extends PhaseReference { public final long delay; public PhaseReferenceDelay(String phase, RelativeIteration iteration, String fork, long delay) { super(phase, iteration, fork); this.delay = delay; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/RelativeIteration.java
api/src/main/java/io/hyperfoil/api/config/RelativeIteration.java
package io.hyperfoil.api.config; public enum RelativeIteration { NONE, PREVIOUS, SAME }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/PluginBuilder.java
api/src/main/java/io/hyperfoil/api/config/PluginBuilder.java
package io.hyperfoil.api.config; import java.util.Map; public abstract class PluginBuilder<E> { protected final BenchmarkBuilder parent; public PluginBuilder(BenchmarkBuilder parent) { this.parent = parent; } public abstract E ergonomics(); public abstract void prepareBuild(); public void addTags(Map<String, Object> tags) { } public abstract PluginConfig build(); public BenchmarkBuilder endPlugin() { return parent; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/BenchmarkBuilder.java
api/src/main/java/io/hyperfoil/api/config/BenchmarkBuilder.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.api.config; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.Function; import java.util.stream.Collectors; import io.hyperfoil.impl.FutureSupplier; /** * @author <a href="mailto:stalep@gmail.com">Ståle Pedersen</a> */ public class BenchmarkBuilder { private final BenchmarkSource source; private final Map<String, String> params; private BenchmarkData data; private String name; private Map<String, String> defaultAgentProperties = Collections.emptyMap(); private final Collection<Agent> agents = new ArrayList<>(); private final Map<Class<? extends PluginBuilder<?>>, PluginBuilder<?>> plugins = new HashMap<>(); private int threads = 1; private final Map<String, PhaseBuilder<?>> phaseBuilders = new HashMap<>(); private long statisticsCollectionPeriod = 1000; private String triggerUrl; private final List<RunHook> preHooks = new ArrayList<>(); private final List<RunHook> postHooks = new ArrayList<>(); private Benchmark.FailurePolicy failurePolicy = Benchmark.FailurePolicy.CANCEL; public static Collection<PhaseBuilder<?>> phasesForTesting(BenchmarkBuilder builder) { return builder.phaseBuilders.values(); } public BenchmarkBuilder(BenchmarkSource source, Map<String, String> params) { this.source = source; this.params = params; this.data = source == null ? BenchmarkData.EMPTY : source.data; } public static BenchmarkBuilder builder() { return new BenchmarkBuilder(null, Collections.emptyMap()); } public BenchmarkSource source() { return source; } public BenchmarkBuilder name(String name) { this.name = name; return this; } public String name() { return name; } public BenchmarkBuilder addAgent(String name, String inlineConfig, Map<String, String> properties) { Agent agent = new Agent(name, inlineConfig, properties); if (agents.stream().anyMatch(a -> a.name.equals(agent.name))) { throw new BenchmarkDefinitionException("Benchmark already contains agent '" + agent.name + "'"); } agents.add(agent); return this; } int numAgents() { return agents.size(); } public BenchmarkBuilder threads(int threads) { this.threads = threads; return this; } public PhaseBuilder.Catalog addPhase(String name) { return new PhaseBuilder.Catalog(this, name); } public PhaseBuilder.ConstantRate singleConstantRatePhase() { if (phaseBuilders.isEmpty()) { return new PhaseBuilder.Catalog(this, "main").constantRate(0); } PhaseBuilder<?> builder = phaseBuilders.get("main"); if (!(builder instanceof PhaseBuilder.ConstantRate)) { throw new BenchmarkDefinitionException("Benchmark already has defined phases; cannot use single-phase definition"); } return (PhaseBuilder.ConstantRate) builder; } public BenchmarkBuilder triggerUrl(String url) { this.triggerUrl = url; return this; } public BenchmarkBuilder addPreHook(RunHook runHook) { preHooks.add(runHook); return this; } public BenchmarkBuilder addPostHook(RunHook runHook) { postHooks.add(runHook); return this; } public BenchmarkBuilder failurePolicy(Benchmark.FailurePolicy policy) { failurePolicy = policy; return this; } public void prepareBuild() { plugins.values().forEach(PluginBuilder::prepareBuild); phaseBuilders.values().forEach(PhaseBuilder::prepareBuild); } public Benchmark build() { prepareBuild(); FutureSupplier<Benchmark> bs = new FutureSupplier<>(); AtomicInteger phaseIdCounter = new AtomicInteger(0); Map<String, Phase> phases = phaseBuilders.values().stream() .flatMap(builder -> builder.build(bs, phaseIdCounter).stream()).collect(Collectors.toMap(Phase::name, p -> p)); for (Phase phase : phases.values()) { // check if referenced dependencies exist checkDependencies(phase, phase.startAfter, phases); checkDependencies(phase, phase.startAfterStrict, phases); checkDependencies(phase, phase.terminateAfterStrict, phases); if (phase.startWithDelay != null) { checkDependencies(phase, Collections.singletonList(phase.startWithDelay.phase), phases); } checkStartWith(phase); checkDeadlock(phase, phases); } Map<String, Object> tags = new HashMap<>(); plugins.values().forEach(builder -> builder.addTags(tags)); tags.put("threads", threads); // It is important to gather files only after all other potentially file-reading builders // are done. Map<String, byte[]> files = data.files(); Agent[] agents = this.agents.stream().map(a -> { HashMap<String, String> properties = new HashMap<>(defaultAgentProperties); properties.putAll(a.properties); return new Agent(a.name, a.inlineConfig, properties); }).toArray(Agent[]::new); Map<Class<? extends PluginConfig>, PluginConfig> plugins = this.plugins.values().stream() .map(PluginBuilder::build).collect(Collectors.toMap(PluginConfig::getClass, Function.identity())); Benchmark benchmark = new Benchmark(name, Benchmark.randomUUID(), source, params, files, agents, threads, plugins, new ArrayList<>(phases.values()), tags, statisticsCollectionPeriod, triggerUrl, preHooks, postHooks, failurePolicy); bs.set(benchmark); return benchmark; } private void checkDeadlock(Phase phase, Map<String, Phase> phases) { // prevent deadlock Map<Phase, Phase> deps = new HashMap<>(); Queue<Phase> toProcess = new ArrayDeque<>(); toProcess.add(phase); while (!toProcess.isEmpty()) { Phase p = toProcess.poll(); // consider all referenced dependencies (startAfter, startAfterStrict and startWithDelay) // ensure there are no cyclic references. p.getDependencies().forEach(name -> { Phase p2 = phases.get(name); if (p2 == null) { // non-existent phase, will be reported later return; } else if (p2 == phase) { StringBuilder sb = new StringBuilder("Phase dependencies contain cycle: ").append(name).append(" > "); Phase p3 = p; do { sb.append(p3.name).append(" > "); p3 = deps.get(p3); assert p3 != null; } while (p3 != phase); throw new BenchmarkDefinitionException(sb.append(name).toString()); } if (deps.putIfAbsent(p2, p) == null) { toProcess.add(p2); } }); } } private void checkDependencies(Phase phase, Collection<String> references, Map<String, Phase> phases) { for (String dep : references) { if (!phases.containsKey(dep)) { String suggestion = phases.keySet().stream() .filter(name -> name.toLowerCase().startsWith(dep)).findAny() .map(name -> " Did you mean " + name + "?").orElse(""); throw new BenchmarkDefinitionException( "Phase " + dep + " referenced from " + phase.name() + " is not defined." + suggestion); } } } /** * Check that a phase does not have both startWith and any other start* set * * @param phase phase to check */ private void checkStartWith(Phase phase) { if (phase.startWithDelay != null && (!phase.startAfter.isEmpty() || !phase.startAfterStrict.isEmpty() || phase.startTime > 0)) { throw new BenchmarkDefinitionException( "Phase " + phase.name + " has both startWith and one of startAfter, startAfterStrict and startTime set."); } } void addPhase(String name, PhaseBuilder phaseBuilder) { if (phaseBuilders.containsKey(name)) { throw new IllegalArgumentException("Phase '" + name + "' already defined."); } phaseBuilders.put(name, phaseBuilder); } public BenchmarkBuilder statisticsCollectionPeriod(long statisticsCollectionPeriod) { this.statisticsCollectionPeriod = statisticsCollectionPeriod; return this; } public BenchmarkData data() { return data; } public BenchmarkBuilder data(BenchmarkData data) { this.data = data; return this; } public BenchmarkBuilder setDefaultAgentProperties(Map<String, String> properties) { this.defaultAgentProperties = properties; return this; } @SuppressWarnings("unchecked") public <T extends PluginBuilder<?>> T plugin(Class<T> clz) { return (T) plugins.get(clz); } public <P extends PluginBuilder<?>> P addPlugin(Function<BenchmarkBuilder, P> ctor) { P plugin = ctor.apply(this); @SuppressWarnings("unchecked") Class<? extends PluginBuilder<?>> pluginClass = (Class<? extends PluginBuilder<?>>) plugin.getClass(); PluginBuilder<?> prev = plugins.putIfAbsent(pluginClass, plugin); if (prev != null) { throw new BenchmarkDefinitionException("Adding the same plugin twice! " + plugin.getClass().getName()); } return plugin; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/Benchmark.java
api/src/main/java/io/hyperfoil/api/config/Benchmark.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.api.config; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.IntStream; import java.util.stream.Stream; /** * A benchmark is a collection of simulation, user, * SLA and scaling strategy (Ramp up, Steady State, Ramp Down, steady state variance) * that are to be run against the target environment. */ public class Benchmark implements Serializable { private final String name; private final String version; private final Map<String, String> params; @Visitor.Ignore private final BenchmarkSource source; @Visitor.Ignore private final Map<String, byte[]> files; private final Agent[] agents; private final int defaultThreads; private final int totalThreads; @Visitor.Invoke(method = "plugins") private final Map<Class<? extends PluginConfig>, PluginConfig> plugins; private final Collection<Phase> phases; private final Map<String, Object> tags; private final long statisticsCollectionPeriod; private final String triggerUrl; private final List<RunHook> preHooks; private final List<RunHook> postHooks; private final FailurePolicy failurePolicy; public static Benchmark forTesting() { return BenchmarkBuilder.builder().build(); } public Benchmark(String name, String version, BenchmarkSource source, Map<String, String> params, Map<String, byte[]> files, Agent[] agents, int defaultThreads, Map<Class<? extends PluginConfig>, PluginConfig> plugins, Collection<Phase> phases, Map<String, Object> tags, long statisticsCollectionPeriod, String triggerUrl, List<RunHook> preHooks, List<RunHook> postHooks, FailurePolicy failurePolicy) { this.name = name; this.params = params; this.source = source; this.files = files; this.agents = agents; this.defaultThreads = defaultThreads; this.plugins = plugins; this.failurePolicy = failurePolicy; this.totalThreads = agents.length == 0 ? defaultThreads : Stream.of(agents).mapToInt(Agent::threads).map(n -> n <= 0 ? defaultThreads : n).sum(); this.phases = phases; this.tags = tags; this.statisticsCollectionPeriod = statisticsCollectionPeriod; this.triggerUrl = triggerUrl; this.preHooks = preHooks; this.postHooks = postHooks; this.version = version; } static String randomUUID() { ThreadLocalRandom random = ThreadLocalRandom.current(); return new UUID(random.nextLong(), random.nextLong()).toString(); } public static Benchmark empty(String name, Map<String, String> templateParams) { return new Benchmark(name, randomUUID(), null, templateParams, Collections.emptyMap(), new Agent[0], 0, Collections.emptyMap(), Collections.emptyList(), Collections.emptyMap(), 0, null, Collections.emptyList(), Collections.emptyList(), FailurePolicy.CANCEL); } public String name() { return name; } public String version() { return version; } public Agent[] agents() { return agents; } /** * As the transformation from YAML is one-way (due to forks and iterations) * here we store the original source (be it YAML or JSON) * * @return Source YAML for the benchmark. */ public BenchmarkSource source() { return source; } public Map<String, String> params() { return params; } public Map<String, byte[]> files() { return files; } public int defaultThreads() { return defaultThreads; } public Collection<Phase> phases() { return phases; } public Map<String, Object> tags() { return tags; } public long statisticsCollectionPeriod() { return statisticsCollectionPeriod; } public String triggerUrl() { return triggerUrl; } public List<RunHook> preHooks() { return preHooks; } public List<RunHook> postHooks() { return postHooks; } @Override public String toString() { return "Benchmark{name='" + name + '\'' + ", source='" + source + '\'' + ", agents=" + Arrays.toString(agents) + ", threads=" + defaultThreads + ", plugins=" + plugins + ", phases=" + phases + ", tags=" + tags + ", statisticsCollectionPeriod=" + statisticsCollectionPeriod + '}'; } public Stream<Step> steps() { return phases().stream() .flatMap(phase -> Stream.of(phase.scenario().sequences())) .flatMap(sequence -> Stream.of(sequence.steps())); } public Phase[] phasesById() { Phase[] phases = new Phase[this.phases.size()]; this.phases.forEach(p -> phases[p.id()] = p); return phases; } public int slice(int totalValue, int agentId) { if (agents.length == 0) { return totalValue; } int threads = threads(agentId); int prevThreads = IntStream.range(0, agentId).map(this::threads).sum(); return (prevThreads + threads) * totalValue / totalThreads - prevThreads * totalValue / totalThreads; } public double slice(double totalValue, int agentId) { if (agents.length == 0) { return totalValue; } return totalValue * threads(agentId) / totalThreads; } public int threads(int agentId) { if (agents.length == 0) { return defaultThreads; } int threads = agents()[agentId].threads(); return threads <= 0 ? defaultThreads() : threads; } public int totalThreads() { return totalThreads; } @SuppressWarnings("unchecked") public <T extends PluginConfig> T plugin(Class<T> clazz) { return (T) plugins.get(clazz); } public Collection<PluginConfig> plugins() { return plugins.values(); } public FailurePolicy failurePolicy() { return failurePolicy; } public enum FailurePolicy { CANCEL, CONTINUE, } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/BuilderBase.java
api/src/main/java/io/hyperfoil/api/config/BuilderBase.java
package io.hyperfoil.api.config; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.Map; /** * Intended base for all builders that might need relocation when the step is copied over. */ public interface BuilderBase<S extends BuilderBase<S>> { default void prepareBuild() { Class<?> clz = getClass(); while (clz != null && clz != Object.class) { for (Field f : clz.getDeclaredFields()) { if (f.isSynthetic() || Modifier.isStatic(f.getModifiers()) || "parent".equals(f.getName())) { continue; } f.setAccessible(true); try { tryPrepare(clz, f.getName(), f.getType(), f.get(this)); } catch (IllegalAccessException e) { throw new UnsupportedOperationException( "Cannot get value of " + clz.getName() + "." + f.getName() + " (actual instance: " + this + ")"); } } clz = clz.getSuperclass(); } } private void tryPrepare(Class<?> clz, String name, Class<?> type, Object value) throws IllegalAccessException { if (BuilderBase.class.isAssignableFrom(type)) { if (value != null) { ((BuilderBase<?>) value).prepareBuild(); } } else if (Collection.class.isAssignableFrom(type)) { if (value != null) { for (Object item : (Collection<?>) value) { if (item != null) { tryPrepare(clz, name, item.getClass(), item); } } } } else if (BaseSequenceBuilder.class.isAssignableFrom(type)) { if (value != null) { ((BaseSequenceBuilder<?>) value).prepareBuild(); } } else if (Map.class.isAssignableFrom(type)) { if (value != null) { for (Map.Entry<?, ?> entry : ((Map<?, ?>) value).entrySet()) { if (entry.getKey() != null) { tryPrepare(clz, name, entry.getKey().getClass(), entry.getKey()); } if (entry.getValue() != null) { tryPrepare(clz, name, entry.getValue().getClass(), entry.getValue()); } } } } else if (type.isArray()) { throw new UnsupportedOperationException(clz.getName() + "." + name + " is an array (actual instance: " + this + ")"); } } /** * Some scenarios copy its parts from one place to another, either during parsing * phase (e.g. through YAML anchors) or in {@link #prepareBuild()}. * In order to make sure that modification in one place does not accidentally change * the original one we require defining a deep copy method on each builder. The only * exception is when the builder is immutable (including potential children builder); * in that case the deep copy is not necessary and this method can return <code>this</code>. * <p> * The default implementation uses reflection to create a deep copy of all collections and maps, * calling <code>copy()</code> on all objects implementing {@link BuilderBase}. * * @param newParent Object passed to a matching constructor. * @return Deep copy of this object. */ @SuppressWarnings("unchecked") default S copy(Object newParent) { if (getClass().isSynthetic()) { // This is most likely a lambda supplier of the instance (which should be immutable anyway) assert getClass().getSimpleName().contains("$$Lambda"); return (S) this; } try { ThrowingSupplier<BuilderBase<?>> constructor = null; for (Constructor<?> ctor : getClass().getConstructors()) { // parameterless constructor has lowest priority if (ctor.getParameterCount() == 0 && constructor == null) { constructor = () -> (BuilderBase<?>) ctor.newInstance(); } else if (ctor.getParameterCount() == 1) { Class<?> parameterType = ctor.getParameterTypes()[0]; if (parameterType == getClass()) { constructor = () -> (BuilderBase<?>) ctor.newInstance(this); // copy constructor has highest priority break; } else if (newParent != null && parameterType.isAssignableFrom(newParent.getClass())) { constructor = () -> (BuilderBase<?>) ctor.newInstance(newParent); } } } if (constructor == null) { throw new NoSuchMethodException("No constructor for " + getClass().getName()); } BuilderBase<?> copy = constructor.get(); Class<?> cls = getClass(); while (cls != null && cls != BuilderBase.class) { for (Field f : cls.getDeclaredFields()) { f.setAccessible(true); if (Modifier.isStatic(f.getModifiers())) { // do not copy static fields } else if (f.isAnnotationPresent(IgnoreCopy.class)) { // field is intentionally omitted } else if (Modifier.isFinal(f.getModifiers())) { Object thisValue = f.get(this); Object copyValue = f.get(copy); if (thisValue == copyValue) { // usually happens when the value is null } else if (copyValue instanceof Collection) { // final collections can only get the elements Collection<Object> copyCollection = (Collection<Object>) copyValue; copyCollection.clear(); copyCollection.addAll((Collection<?>) CopyUtil.deepCopy(thisValue, copy)); } else if (f.getName().equals("parent")) { // Fluent builders often require parent element reference; in YAML configuration these are not used. } else if (copyValue instanceof BaseSequenceBuilder && thisValue instanceof BaseSequenceBuilder) { List<StepBuilder<?>> newSteps = ((BaseSequenceBuilder<?>) copyValue).steps; ((BaseSequenceBuilder<?>) thisValue).steps.forEach(sb -> newSteps.add(sb.copy(copyValue))); } else { // This could be e.g. final list and we wouldn't copy it throw new UnsupportedOperationException( cls.getName() + "." + f.getName() + " is final (actual instance: " + this + ")"); } } else if (f.getType().isPrimitive()) { if (f.getType() == boolean.class) { f.setBoolean(copy, f.getBoolean(this)); } else if (f.getType() == int.class) { f.setInt(copy, f.getInt(this)); } else if (f.getType() == long.class) { f.setLong(copy, f.getLong(this)); } else if (f.getType() == double.class) { f.setDouble(copy, f.getDouble(this)); } else if (f.getType() == float.class) { f.setFloat(copy, f.getFloat(this)); } else if (f.getType() == byte.class) { f.setByte(copy, f.getByte(this)); } else if (f.getType() == char.class) { f.setChar(copy, f.getChar(this)); } else if (f.getType() == short.class) { f.setShort(copy, f.getShort(this)); } else { throw new UnsupportedOperationException("Unknown primitive: " + f.getType()); } } else if (f.getType().isArray()) { if (f.getType().getComponentType() == byte.class) { byte[] bytes = (byte[]) f.get(this); f.set(copy, bytes == null ? null : Arrays.copyOf(bytes, bytes.length)); } else { // use list in builders throw new UnsupportedOperationException( cls.getName() + "." + f.getName() + " is an array (actual instance: " + this + ")"); } } else { f.set(copy, CopyUtil.deepCopy(f.get(this), copy)); } } cls = cls.getSuperclass(); } return (S) copy; } catch (ReflectiveOperationException e) { throw new BenchmarkDefinitionException("Default deep copy failed", e); } } interface ThrowingSupplier<T> { T get() throws ReflectiveOperationException; } class CopyUtil { private static Object deepCopy(Object o, Object newParent) throws ReflectiveOperationException { if (o == null) { return null; } else if (BuilderBase.class.isAssignableFrom(o.getClass())) { return ((BuilderBase<?>) o).copy(newParent); } else if (Collection.class.isAssignableFrom(o.getClass())) { Collection<?> thisCollection = (Collection<?>) o; @SuppressWarnings("unchecked") Collection<Object> newCollection = thisCollection.getClass().getConstructor().newInstance(); for (Object item : thisCollection) { newCollection.add(deepCopy(item, newParent)); } return newCollection; } else if (Map.class.isAssignableFrom(o.getClass())) { Map<?, ?> thisMap = (Map<?, ?>) o; @SuppressWarnings("unchecked") Map<Object, Object> newMap = thisMap.getClass().getConstructor().newInstance(); for (Map.Entry<?, ?> entry : thisMap.entrySet()) { newMap.put(deepCopy(entry.getKey(), null), deepCopy(entry.getValue(), newParent)); } return newMap; } else { return o; } } } /** * Used to ignore copying the field (e.g. when it's final, or we don't want to call it 'parent'). */ @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) @interface IgnoreCopy { } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/ListBuilder.java
api/src/main/java/io/hyperfoil/api/config/ListBuilder.java
package io.hyperfoil.api.config; public interface ListBuilder { void nextItem(String key); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/PhaseForkBuilder.java
api/src/main/java/io/hyperfoil/api/config/PhaseForkBuilder.java
package io.hyperfoil.api.config; public class PhaseForkBuilder { public final String name; public final ScenarioBuilder scenario; double weight = 1; public PhaseForkBuilder(PhaseBuilder<?> parent, String name) { this.name = name; this.scenario = new ScenarioBuilder(parent, this); } public PhaseForkBuilder weight(double weight) { this.weight = weight; return this; } public ScenarioBuilder scenario() { return scenario; } public void readFrom(PhaseForkBuilder other) { this.weight = other.weight; this.scenario.readFrom(other.scenario); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/ScenarioBuilder.java
api/src/main/java/io/hyperfoil/api/config/ScenarioBuilder.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.api.config; import java.util.ArrayList; import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; /** * @author <a href="mailto:stalep@gmail.com">Ståle Pedersen</a> */ public class ScenarioBuilder { private final PhaseBuilder<?> phaseBuilder; private final PhaseForkBuilder forkBuilder; private List<SequenceBuilder> initialSequences = new ArrayList<>(); private List<SequenceBuilder> sequences = new ArrayList<>(); private Scenario scenario; private int maxRequests = 16; // We don't use sum of concurrency because that could be excessively high private int maxSequences = 16; ScenarioBuilder(PhaseBuilder<?> phaseBuilder, PhaseForkBuilder forkBuilder) { this.phaseBuilder = phaseBuilder; this.forkBuilder = forkBuilder; } public PhaseForkBuilder fork() { return forkBuilder; } public PhaseBuilder<?> endScenario() { return phaseBuilder; } private void initialSequence(SequenceBuilder sequence) { initialSequences.add(sequence); sequence(sequence); } public List<SequenceBuilder> resetInitialSequences() { List<SequenceBuilder> prev = this.initialSequences; initialSequences = new ArrayList<>(); return prev; } public SequenceBuilder initialSequence(String name, SequenceBuilder copyFrom) { SequenceBuilder sequenceBuilder = copyFrom == null ? new SequenceBuilder(this) : copyFrom.copy(this); sequenceBuilder.nextSequence(null); initialSequence(sequenceBuilder.name(name)); return sequenceBuilder; } public SequenceBuilder initialSequence(String name) { SequenceBuilder builder = new SequenceBuilder(this).name(name); initialSequence(builder); return builder; } private void sequence(SequenceBuilder sequence) { sequence.id(sequences.size()); sequences.add(sequence); } public SequenceBuilder sequence(String name, SequenceBuilder copyFrom) { SequenceBuilder sequenceBuilder = copyFrom == null ? new SequenceBuilder(this) : copyFrom.copy(this); sequenceBuilder.nextSequence(null); sequence(sequenceBuilder.name(name)); return sequenceBuilder; } public SequenceBuilder sequence(String name) { SequenceBuilder builder = new SequenceBuilder(this).name(name); sequence(builder); return builder; } public boolean hasSequence(String name) { return sequences.stream().anyMatch(sb -> name.equals(sb.name())); } public SequenceBuilder findSequence(String name) { return sequences.stream().filter(sb -> name.equals(sb.name())).findFirst() .orElseThrow(() -> new BenchmarkDefinitionException("No sequence " + name + " in phase " + endScenario().name())); } public ScenarioBuilder maxRequests(int maxRequests) { this.maxRequests = maxRequests; return this; } public ScenarioBuilder maxSequences(int maxSequences) { this.maxSequences = maxSequences; return this; } public void prepareBuild() { new ArrayList<>(sequences).forEach(SequenceBuilder::prepareBuild); } public Scenario build() { Locator.push(this); try { if (scenario != null) { return scenario; } if (initialSequences.isEmpty()) { throw new BenchmarkDefinitionException("No initial sequences in phase " + endScenario().name()); } Sequence[] initialSequences = new Sequence[this.initialSequences.size()]; int offset = 0; for (int i = 0; i < this.initialSequences.size(); i++) { Sequence sequence = this.initialSequences.get(i).build(offset); initialSequences[i] = sequence; offset += sequence.concurrency() > 0 ? sequence.concurrency() : 1; } Sequence[] sequences = new Sequence[this.sequences.size()]; for (int i = 0; i < this.sequences.size(); i++) { Sequence sequence = this.sequences.get(i).build(offset); sequences[i] = sequence; offset += sequence.concurrency() > 0 ? sequence.concurrency() : 1; } int maxSequences = Math.max(Stream.of(sequences).mapToInt(sequence -> { boolean isInitial = Stream.of(initialSequences).anyMatch(s -> s == sequence); return isInitial ? sequence.concurrency() : sequence.concurrency() + 1; }).max().orElse(1), this.maxSequences); return scenario = new Scenario( initialSequences, sequences, maxRequests, maxSequences); } finally { Locator.pop(); } } public void readFrom(ScenarioBuilder other) { this.sequences = other.sequences.stream() .map(seq -> seq.copy(this)).collect(Collectors.toList()); this.initialSequences = other.initialSequences.stream() .map(seq -> findMatchingSequence(seq.name())).collect(Collectors.toList()); } private SequenceBuilder findMatchingSequence(String name) { return this.sequences.stream().filter(s2 -> s2.name().equals(name)).findFirst().orElseThrow(IllegalStateException::new); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/Scenario.java
api/src/main/java/io/hyperfoil/api/config/Scenario.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.api.config; import java.io.Serializable; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import java.util.stream.Stream; import io.hyperfoil.api.session.AccessVisitor; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.api.session.WriteAccess; public class Scenario implements Serializable { private final Sequence[] initialSequences; private final Sequence[] sequences; private final Map<String, Sequence> sequenceMap; private final int maxRequests; private final int maxSequences; private final int sumConcurrency; private final WriteAccess[] writes; private final int uniqueVars; public Scenario(Sequence[] initialSequences, Sequence[] sequences, int maxRequests, int maxSequences) { this.initialSequences = initialSequences; this.sequences = sequences; this.maxRequests = maxRequests; this.maxSequences = maxSequences; sequenceMap = Stream.of(sequences).collect(Collectors.toMap(Sequence::name, Function.identity())); sumConcurrency = sequenceMap.values().stream().mapToInt(Sequence::concurrency).sum(); AccessVisitor visitor = new AccessVisitor(); visitor.visit(sequences); writes = visitor.writes(); ReadAccess[] reads = visitor.reads(); Set<Object> writtenKeys = Arrays.stream(writes).map(ReadAccess::key).collect(Collectors.toSet()); Set<Object> readKeys = Arrays.stream(reads).map(ReadAccess::key).filter(Objects::nonNull).collect(Collectors.toSet()); readKeys.forEach(key -> { if (!writtenKeys.contains(key)) { // TODO: calculate similar variable names using Levenshtein distance and hint throw new BenchmarkDefinitionException("Variable '" + key + "' is read but it is never written to."); } }); Map<Object, Integer> keyIndexMap = new HashMap<>(); for (Object key : readKeys) { keyIndexMap.put(key, keyIndexMap.size()); } uniqueVars = keyIndexMap.size(); for (ReadAccess access : reads) { if (access.key() != null) { access.setIndex(keyIndexMap.get(access.key())); } } } public Sequence[] initialSequences() { return initialSequences; } public Sequence[] sequences() { return sequences; } public int maxRequests() { return maxRequests; } public int maxSequences() { return maxSequences; } public int sumConcurrency() { return sumConcurrency; } public Sequence sequence(String name) { Sequence sequence = sequenceMap.get(name); if (sequence == null) { throw new IllegalArgumentException("Unknown sequence '" + name + "'"); } return sequence; } public Session.Var[] createVars(Session session) { Session.Var[] vars = new Session.Var[uniqueVars]; for (WriteAccess access : writes) { int index = access.index(); vars[index] = access.createVar(session, vars[index]); } return vars; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/Phase.java
api/src/main/java/io/hyperfoil/api/config/Phase.java
package io.hyperfoil.api.config; import java.io.Serializable; import java.util.Collection; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.function.SerializableSupplier; public final class Phase implements Serializable { protected static final Logger log = LogManager.getLogger(Phase.class); protected static final boolean trace = log.isTraceEnabled(); @Visitor.Ignore protected final SerializableSupplier<Benchmark> benchmark; @Visitor.Ignore public final int id; public final int iteration; @Visitor.Ignore public final String name; public final Scenario scenario; public final long startTime; public final Collection<String> startAfter; public final Collection<String> startAfterStrict; public final Collection<String> terminateAfterStrict; public final long duration; public final long maxDuration; // identifier for sharing resources across iterations public final String sharedResources; public final Model model; public final boolean isWarmup; public final Map<String, SLA[]> customSlas; public final StartWithDelay startWithDelay; public Phase(SerializableSupplier<Benchmark> benchmark, int id, int iteration, String name, Scenario scenario, long startTime, Collection<String> startAfter, Collection<String> startAfterStrict, Collection<String> terminateAfterStrict, long duration, long maxDuration, String sharedResources, boolean isWarmup, Model model, Map<String, SLA[]> customSlas, StartWithDelay startWithDelay) { this.benchmark = benchmark; this.id = id; this.iteration = iteration; this.name = name; this.terminateAfterStrict = terminateAfterStrict; this.maxDuration = maxDuration; this.startAfter = startAfter; this.startAfterStrict = startAfterStrict; this.scenario = scenario; this.startTime = startTime; this.duration = duration; this.sharedResources = sharedResources; this.isWarmup = isWarmup; this.model = model; this.customSlas = customSlas; this.startWithDelay = startWithDelay; if (scenario == null) { throw new BenchmarkDefinitionException("Scenario was not set for phase '" + name + "'"); } model.validate(this); } public int id() { return id; } public String name() { return name; } public Scenario scenario() { return scenario; } /** * @return Start time in milliseconds after benchmark start, or negative value if the phase should start immediately * after its dependencies ({@link #startAfter()} and {@link #startAfterStrict()} are satisfied. */ public long startTime() { return startTime; } /** * @return Phases that must be finished (not starting any further user sessions) in order to start. */ public Collection<String> startAfter() { return startAfter; } /** * @return Phases that must be terminated (not running any user sessions) in order to start. */ public Collection<String> startAfterStrict() { return startAfterStrict; } /** * @return Phases that must be terminated in order to terminate this phase. */ public Collection<String> terminateAfterStrict() { return terminateAfterStrict; } /** * @return Duration in milliseconds over which new user sessions should be started. */ public long duration() { return duration; } /** * @return Duration in milliseconds over which user sessions can run. After this time no more requests are allowed * and the phase should terminate. */ public long maxDuration() { return maxDuration; } public Benchmark benchmark() { return benchmark.get(); } public String description() { return model.description(); } /** * @return Start with delay object defining the phase to which it is coupled, the current phase will start after a * fixed time (delay) from the start of the coupled phase. */ public StartWithDelay startWithDelay() { return startWithDelay; } /** * Compute and return all phase's dependencies * * @return list of phase names */ public Collection<String> getDependencies() { Stream<String> dependencies = Stream.concat(startAfter().stream(), startAfterStrict().stream()); if (startWithDelay() != null) { dependencies = Stream.concat(dependencies, Stream.of(startWithDelay().phase)); } return dependencies.collect(Collectors.toList()); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/PartialBuilder.java
api/src/main/java/io/hyperfoil/api/config/PartialBuilder.java
package io.hyperfoil.api.config; /** * This builder is useful when we want to use custom keys in YAML. */ public interface PartialBuilder { Object withKey(String key); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/BenchmarkSource.java
api/src/main/java/io/hyperfoil/api/config/BenchmarkSource.java
package io.hyperfoil.api.config; import java.io.Serializable; import java.util.Map; public class BenchmarkSource implements Serializable { public final String name; public final String version; public final String yaml; public final transient BenchmarkData data; public final Map<String, String> paramsWithDefaults; public BenchmarkSource(String name, String yaml, BenchmarkData data, Map<String, String> paramsWithDefaults) { this.name = name; // note: version of template and resulting benchmark don't have to match this.version = Benchmark.randomUUID(); this.yaml = yaml; this.data = data; this.paramsWithDefaults = paramsWithDefaults; } public boolean isTemplate() { return !paramsWithDefaults.isEmpty(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/SessionLimitPolicy.java
api/src/main/java/io/hyperfoil/api/config/SessionLimitPolicy.java
package io.hyperfoil.api.config; public enum SessionLimitPolicy { /** * Cancel all sessions that did not start yet if the session limit is reached. */ FAIL, /** * Continue even if we've reached maximum sessions. */ CONTINUE }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/StartWithDelay.java
api/src/main/java/io/hyperfoil/api/config/StartWithDelay.java
package io.hyperfoil.api.config; import java.io.Serializable; public class StartWithDelay implements Serializable { public final String phase; public final long delay; public StartWithDelay(String phase, long delay) { this.phase = phase; this.delay = delay; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/BaseSequenceBuilder.java
api/src/main/java/io/hyperfoil/api/config/BaseSequenceBuilder.java
package io.hyperfoil.api.config; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.NoSuchElementException; import java.util.ServiceLoader; import java.util.stream.Collectors; import io.hyperfoil.impl.StepCatalogFactory; public abstract class BaseSequenceBuilder<S extends BaseSequenceBuilder<S>> implements BuilderBase<S> { private static final Map<Class<? extends Step.Catalog>, StepCatalogFactory> factories = new HashMap<>(); protected final BaseSequenceBuilder<?> parent; protected final List<StepBuilder<?>> steps = new ArrayList<>(); static { ServiceLoader.load(StepCatalogFactory.class).forEach(factory -> factories.put(factory.clazz(), factory)); } public BaseSequenceBuilder(BaseSequenceBuilder<?> parent) { this.parent = parent; } public <D extends Step.Catalog> D step(Class<D> catalogClass) { StepCatalogFactory factory = factories.get(catalogClass); if (factory == null) { throw new IllegalStateException("Cannot load step catalog"); } Step.Catalog catalog = factory.create(this); if (catalogClass.isInstance(catalog)) { return catalogClass.cast(catalog); } else { throw new IllegalStateException("Unknown step catalog " + catalog + ", want: " + catalogClass); } } @SuppressWarnings("unchecked") public S self() { return (S) this; } public S step(Step step) { steps.add(new ProvidedStepBuilder(step)); return self(); } public S step(SimpleBuilder builder) { steps.add(new SimpleAdapter(builder)); return self(); } // Calling this method step() would cause ambiguity with step(Step) defined through lambda public S stepBuilder(StepBuilder<?> stepBuilder) { steps.add(stepBuilder); return self(); } public BaseSequenceBuilder<?> end() { return parent; } public SequenceBuilder rootSequence() { return parent.rootSequence(); } public ScenarioBuilder endSequence() { return rootSequence().endSequence(); } public String name() { return rootSequence().name(); } public BaseSequenceBuilder<?> insertBefore(Locator locator) { return insertWithOffset(locator, 0); } public BaseSequenceBuilder<?> insertAfter(Locator locator) { return insertWithOffset(locator, 1); } private StepInserter insertWithOffset(Locator locator, int offset) { for (int i = 0; i < steps.size(); ++i) { if (steps.get(i) == locator.step()) { StepInserter inserter = new StepInserter(this); steps.add(i + offset, inserter); return inserter; } } throw new NoSuchElementException("Not found: " + locator.step()); } public void prepareBuild() { // We need to make a defensive copy as prepareBuild() may trigger modifications new ArrayList<>(steps).forEach(stepBuilder -> { Locator.push(stepBuilder, BaseSequenceBuilder.this); stepBuilder.prepareBuild(); Locator.pop(); }); } public List<Step> buildSteps() { return steps.stream().map(stepBuilder -> { Locator.push(stepBuilder, BaseSequenceBuilder.this); List<Step> steps = stepBuilder.build(); Locator.pop(); return steps; }).flatMap(List::stream).collect(Collectors.toList()); } public int indexOf(StepBuilder<?> builder) { return steps.indexOf(builder); } public boolean isEmpty() { return steps.isEmpty(); } public int size() { return steps.size(); } /** * Simplified interface that works better with lambdas */ @FunctionalInterface public interface SimpleBuilder { Step build(); } private static class StepInserter extends BaseSequenceBuilder<StepInserter> implements StepBuilder<StepInserter> { private StepInserter(BaseSequenceBuilder<?> parent) { super(parent); } @Override public List<Step> build() { return buildSteps(); } } private static class ProvidedStepBuilder implements StepBuilder<ProvidedStepBuilder> { private final Step step; ProvidedStepBuilder(Step step) { this.step = step; } @Override public List<Step> build() { return Collections.singletonList(step); } @Override public ProvidedStepBuilder copy(Object newParent) { // This builder is immutable return this; } } public static class SimpleAdapter implements StepBuilder<SimpleAdapter> { private final SimpleBuilder builder; public SimpleAdapter(SimpleBuilder builder) { this.builder = builder; } @Override public List<Step> build() { return Collections.singletonList(builder.build()); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/Visitor.java
api/src/main/java/io/hyperfoil/api/config/Visitor.java
package io.hyperfoil.api.config; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Type; public interface Visitor { boolean visit(String name, Object value, Type fieldType); @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @interface Ignore { } @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.FIELD) @interface Invoke { String method(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/PhaseReference.java
api/src/main/java/io/hyperfoil/api/config/PhaseReference.java
package io.hyperfoil.api.config; public class PhaseReference { public final String phase; public final RelativeIteration iteration; public final String fork; public PhaseReference(String phase, RelativeIteration iteration, String fork) { this.phase = phase; this.iteration = iteration; this.fork = fork; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/Name.java
api/src/main/java/io/hyperfoil/api/config/Name.java
package io.hyperfoil.api.config; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Name { String value(); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/BenchmarkData.java
api/src/main/java/io/hyperfoil/api/config/BenchmarkData.java
package io.hyperfoil.api.config; import java.io.File; import java.io.InputStream; import java.util.Collections; import java.util.Map; public interface BenchmarkData { BenchmarkData EMPTY = new BenchmarkData() { @Override public InputStream readFile(String file) { throw new MissingFileException(file, "Cannot load file " + file + " (file set is empty).", null); } @Override public Map<String, byte[]> files() { return Collections.emptyMap(); } }; static String sanitize(String file) { return file.replace(File.separatorChar, '_').replace(File.pathSeparatorChar, '_'); } InputStream readFile(String file); Map<String, byte[]> files(); class MissingFileException extends RuntimeException { public final String file; public MissingFileException(String file) { this.file = file; } public MissingFileException(String file, String message, Throwable cause) { super(message, cause); this.file = file; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/config/PairBuilder.java
api/src/main/java/io/hyperfoil/api/config/PairBuilder.java
package io.hyperfoil.api.config; import java.util.function.BiConsumer; public interface PairBuilder<V> extends BiConsumer<String, V> { Class<V> valueType(); abstract class OfString implements PairBuilder<String> { @Override public Class<String> valueType() { return String.class; } } abstract class OfDouble implements PairBuilder<Double> { @Override public Class<Double> valueType() { return double.class; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/deployment/Deployer.java
api/src/main/java/io/hyperfoil/api/deployment/Deployer.java
package io.hyperfoil.api.deployment; import java.io.Closeable; import java.util.function.Consumer; import io.hyperfoil.api.config.Agent; import io.hyperfoil.api.config.Benchmark; import io.vertx.core.AsyncResult; import io.vertx.core.Handler; public interface Deployer extends Closeable { DeployedAgent start(Agent agent, String runId, Benchmark benchmark, Consumer<Throwable> exceptionHandler); boolean hasControllerLog(); void downloadControllerLog(long offset, long maxLength, String destinationFile, Handler<AsyncResult<Void>> handler); void downloadAgentLog(DeployedAgent deployedAgent, long offset, long maxLength, String destinationFile, Handler<AsyncResult<Void>> handler); interface Factory { String name(); Deployer create(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/deployment/DeployedAgent.java
api/src/main/java/io/hyperfoil/api/deployment/DeployedAgent.java
package io.hyperfoil.api.deployment; public interface DeployedAgent { void stop(); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/deployment/DeploymentException.java
api/src/main/java/io/hyperfoil/api/deployment/DeploymentException.java
package io.hyperfoil.api.deployment; public class DeploymentException extends Exception { public DeploymentException(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/api/src/main/java/io/hyperfoil/api/statistics/Counters.java
api/src/main/java/io/hyperfoil/api/statistics/Counters.java
package io.hyperfoil.api.statistics; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.stream.Collectors; import org.kohsuke.MetaInfServices; import com.fasterxml.jackson.annotation.JsonAnyGetter; import com.fasterxml.jackson.annotation.JsonAnySetter; import com.fasterxml.jackson.annotation.JsonTypeName; @MetaInfServices(StatsExtension.class) @JsonTypeName("counters") public class Counters implements StatsExtension { final Map<Object, Integer> indices; long[] counters; public Counters() { this(new HashMap<>(), new long[8]); } public Counters(Map<Object, Integer> indices, long[] counters) { this.indices = indices; this.counters = counters; } @Override public boolean isNull() { for (int i = 0; i < counters.length; ++i) { if (counters[i] > 0) { return false; } } return true; } public void increment(Object name) { int index = getIndex(name); counters[index]++; } private int getIndex(Object header) { Integer currentIndex = indices.get(header); if (currentIndex == null) { int nextIndex = indices.size(); if (nextIndex == counters.length) { counters = Arrays.copyOf(counters, counters.length * 2); } currentIndex = nextIndex; indices.put(header, currentIndex); } return currentIndex; } @Override public void add(StatsExtension other) { if (other instanceof Counters) { Counters o = (Counters) other; for (Object header : o.indices.keySet()) { int index = getIndex(header); counters[index] += o.counters[o.indices.get(header)]; } } else { throw new IllegalArgumentException(other.toString()); } } @Override public void subtract(StatsExtension other) { if (other instanceof Counters) { Counters o = (Counters) other; for (Object header : o.indices.keySet()) { int index = getIndex(header); counters[index] -= o.counters[o.indices.get(header)]; } } else { throw new IllegalArgumentException(other.toString()); } } @Override public void reset() { Arrays.fill(counters, 0); } @SuppressWarnings("MethodDoesntCallSuperMethod") @Override public StatsExtension clone() { return new Counters(new HashMap<>(indices), Arrays.copyOf(counters, counters.length)); } @Override public String[] headers() { return indices.keySet().stream().map(Object::toString).toArray(String[]::new); } @Override public String byHeader(String header) { for (var entry : indices.entrySet()) { if (entry.getKey().toString().equals(header)) { return String.valueOf(counters[entry.getValue()]); } } return "<unknown header: " + header + ">"; } @JsonAnyGetter public Map<String, Long> serialize() { return indices.entrySet().stream().collect(Collectors.toMap(e -> e.getKey().toString(), e -> counters[e.getValue()])); } @JsonAnySetter public void set(String key, long value) { int index = getIndex(key); counters[index] = value; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/statistics/Statistics.java
api/src/main/java/io/hyperfoil/api/statistics/Statistics.java
package io.hyperfoil.api.statistics; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.function.Consumer; import java.util.function.Supplier; import org.HdrHistogram.SingleWriterRecorder; import org.HdrHistogram.WriterReaderPhaser; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; /** * This is a copy/subset of {@link SingleWriterRecorder} but uses {@link StatisticsSnapshot} instead of only * the histogram. */ public class Statistics { private static final Logger log = LogManager.getLogger(Statistics.class); private static final long SAMPLING_PERIOD_MILLIS = TimeUnit.SECONDS.toMillis(1); private static final ThreadLocal<Long> lastWarnThrottle = ThreadLocal.withInitial(() -> Long.MIN_VALUE); private static final AtomicIntegerFieldUpdater<Statistics> LU1 = AtomicIntegerFieldUpdater.newUpdater(Statistics.class, "lowestActive1"); private static final AtomicIntegerFieldUpdater<Statistics> LU2 = AtomicIntegerFieldUpdater.newUpdater(Statistics.class, "lowestActive2"); private final WriterReaderPhaser recordingPhaser = new WriterReaderPhaser(); private final long highestTrackableValue; // We'll start making space 4 samples (seconds) ahead; in case the readers fall behind the schedule // this will help to keep the active array always big enough. private int numSamples = 4; @SuppressWarnings("unused") private volatile int lowestActive1; @SuppressWarnings("unused") private volatile int lowestActive2; private volatile int highestActive; @SuppressWarnings("AtomicFieldUpdaterNotStaticFinal") private volatile AtomicIntegerFieldUpdater<Statistics> lowestActiveUpdater = LU1; private volatile AtomicReferenceArray<StatisticsSnapshot> active; private AtomicReferenceArray<StatisticsSnapshot> inactive; private long startTimestamp; private long endTimestamp = Long.MAX_VALUE; private int lastLowestIndex; public Statistics(long startTimestamp) { this.startTimestamp = startTimestamp; active = new AtomicReferenceArray<>(16); inactive = new AtomicReferenceArray<>(16); StatisticsSnapshot first = new StatisticsSnapshot(); first.sequenceId = 0; active.set(0, first); highestTrackableValue = first.histogram.getHighestTrackableValue(); } public void recordResponse(long startTimestamp, long responseTime) { if (responseTime > highestTrackableValue) { // we don't use auto-resize histograms long lastWarn = lastWarnThrottle.get(); long warnings = lastWarn & 0xFFFF; long now = System.currentTimeMillis(); if (now - (lastWarn >> 16) > 100) { log.warn("Response time {} exceeded maximum trackable response time {}", responseTime, highestTrackableValue); if (warnings > 0) { log.warn("Response time was also exceeded {} times since last warning", warnings); } lastWarnThrottle.set(now << 16); } else if (warnings < 0xFFFF) { lastWarnThrottle.set(lastWarn + 1); } responseTime = highestTrackableValue; } else if (responseTime < 0) { log.warn("Response time {} is negative.", responseTime); responseTime = 0; } long criticalValueAtEnter = recordingPhaser.writerCriticalSectionEnter(); try { StatisticsSnapshot active = active(startTimestamp); active.histogram.recordValue(responseTime); active.responseCount++; } finally { recordingPhaser.writerCriticalSectionExit(criticalValueAtEnter); } } public void incrementRequests(long timestamp) { long criticalValueAtEnter = recordingPhaser.writerCriticalSectionEnter(); try { StatisticsSnapshot active = active(timestamp); active.requestCount++; } finally { recordingPhaser.writerCriticalSectionExit(criticalValueAtEnter); } } public void incrementTimeouts(long timestamp) { long criticalValueAtEnter = recordingPhaser.writerCriticalSectionEnter(); try { StatisticsSnapshot active = active(timestamp); active.requestTimeouts++; } finally { recordingPhaser.writerCriticalSectionExit(criticalValueAtEnter); } } public void incrementConnectionErrors(long timestamp) { long criticalValueAtEnter = recordingPhaser.writerCriticalSectionEnter(); try { StatisticsSnapshot active = active(timestamp); active.connectionErrors++; } finally { recordingPhaser.writerCriticalSectionExit(criticalValueAtEnter); } } public void incrementInternalErrors(long timestamp) { long criticalValueAtEnter = recordingPhaser.writerCriticalSectionEnter(); try { StatisticsSnapshot active = active(timestamp); active.internalErrors++; } finally { recordingPhaser.writerCriticalSectionExit(criticalValueAtEnter); } } public void incrementBlockedTime(long timestamp, long blockedTime) { long criticalValueAtEnter = recordingPhaser.writerCriticalSectionEnter(); try { StatisticsSnapshot active = active(timestamp); active.blockedTime += blockedTime; } finally { recordingPhaser.writerCriticalSectionExit(criticalValueAtEnter); } } public <C extends StatsExtension> void update(String key, long timestamp, Supplier<C> creator, LongUpdater<C> updater, long value) { long criticalValueAtEnter = recordingPhaser.writerCriticalSectionEnter(); try { StatisticsSnapshot active = active(timestamp); StatsExtension custom = active.extensions.get(key); if (custom == null) { custom = creator.get(); active.extensions.put(key, custom); } //noinspection unchecked updater.update((C) custom, value); } finally { recordingPhaser.writerCriticalSectionExit(criticalValueAtEnter); } } public <C extends StatsExtension> void update(String key, long timestamp, Supplier<C> creator, ObjectUpdater<C> updater, Object value) { long criticalValueAtEnter = recordingPhaser.writerCriticalSectionEnter(); try { StatisticsSnapshot active = active(timestamp); StatsExtension custom = active.extensions.get(key); if (custom == null) { custom = creator.get(); active.extensions.put(key, custom); } //noinspection unchecked updater.update((C) custom, value); } finally { recordingPhaser.writerCriticalSectionExit(criticalValueAtEnter); } } public void addInvalid(long timestamp) { long criticalValueAtEnter = recordingPhaser.writerCriticalSectionEnter(); try { StatisticsSnapshot active = active(timestamp); active.invalid++; } finally { recordingPhaser.writerCriticalSectionExit(criticalValueAtEnter); } } public void visitSnapshots(Consumer<StatisticsSnapshot> consumer) { try { recordingPhaser.readerLock(); if (++numSamples >= inactive.length()) { AtomicReferenceArray<StatisticsSnapshot> temp = new AtomicReferenceArray<>(inactive.length() * 2); for (int i = lastLowestIndex; i < inactive.length(); ++i) { temp.set(i, inactive.get(i)); } inactive = temp; } // Swap active and inactive histograms: final AtomicReferenceArray<StatisticsSnapshot> tempHistogram = inactive; inactive = active; active = tempHistogram; AtomicIntegerFieldUpdater<Statistics> inactiveUpdater = lowestActiveUpdater; lowestActiveUpdater = inactiveUpdater == LU1 ? LU2 : LU1; // Make sure we are not in the middle of recording a value on the previously active histogram: // Flip phase to make sure no recordings that were in flight pre-flip are still active: recordingPhaser.flipPhase(500000L /* yield in 0.5 msec units if needed */); lastLowestIndex = Math.min(LU1.get(this), LU2.get(this)); int maxSamples; // If the statistics is not finished don't publish the last timestamp // as this might be shortened be the termination of the phase. if (endTimestamp != Long.MAX_VALUE) { maxSamples = Math.min(inactive.length(), highestActive + 1); } else { maxSamples = Math.min(inactive.length() - 1, highestActive); } // Make sure that few flips later we'll fetch the stats inactiveUpdater.set(this, maxSamples); publish(inactive, maxSamples, consumer); if (endTimestamp != Long.MAX_VALUE) { // all requests must be complete, let's scan the 'active' as well publish(active, maxSamples, consumer); } } finally { recordingPhaser.readerUnlock(); } } private void publish(AtomicReferenceArray<StatisticsSnapshot> array, int limit, Consumer<StatisticsSnapshot> consumer) { for (int i = lastLowestIndex; i < limit; ++i) { StatisticsSnapshot snapshot = array.get(i); if (snapshot == null) { // nothing to do } else if (snapshot.isEmpty()) { array.set(i, null); } else { snapshot.histogram.setStartTimeStamp(startTimestamp + i * SAMPLING_PERIOD_MILLIS); snapshot.histogram.setEndTimeStamp(Math.min(endTimestamp, startTimestamp + (i + 1) * SAMPLING_PERIOD_MILLIS)); consumer.accept(snapshot); snapshot.reset(); } } } public void start(long now) { recordingPhaser.readerLock(); try { startTimestamp = now; endTimestamp = Long.MAX_VALUE; } finally { recordingPhaser.readerUnlock(); } } public void end(long now) { recordingPhaser.readerLock(); try { endTimestamp = now; } finally { recordingPhaser.readerUnlock(); } } private StatisticsSnapshot active(long timestamp) { int index = (int) ((timestamp - startTimestamp) / SAMPLING_PERIOD_MILLIS); AtomicReferenceArray<StatisticsSnapshot> active = this.active; if (index >= active.length()) { index = active.length() - 1; } else if (index < 0) { log.error("Record start timestamp {} predates statistics start {}", timestamp, startTimestamp); index = 0; } StatisticsSnapshot snapshot = active.get(index); if (snapshot == null) { snapshot = new StatisticsSnapshot(); snapshot.sequenceId = index; active.set(index, snapshot); } lowestActiveUpdater.accumulateAndGet(this, index, Math::min); // Highest active is increasing monotonically and it is updated only by the event-loop thread; // therefore we don't have to use CAS operation if (index > highestActive) { highestActive = index; } return snapshot; } public interface LongUpdater<C extends StatsExtension> { void update(C custom, long value); } public interface ObjectUpdater<C extends StatsExtension> { void update(C custom, Object value); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/statistics/StatsExtension.java
api/src/main/java/io/hyperfoil/api/statistics/StatsExtension.java
package io.hyperfoil.api.statistics; import java.io.Serializable; import java.util.ServiceLoader; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.databind.jsontype.NamedType; import io.vertx.core.json.jackson.DatabindCodec; @JsonTypeInfo(use = JsonTypeInfo.Id.NAME) public interface StatsExtension extends Serializable, Cloneable { static void registerSubtypes() { ServiceLoader.load(StatsExtension.class).stream().forEach(provider -> { JsonTypeName typeName = provider.type().getAnnotation(JsonTypeName.class); if (typeName != null) { NamedType namedType = new NamedType(provider.type(), typeName.value()); DatabindCodec.mapper().registerSubtypes(namedType); DatabindCodec.prettyMapper().registerSubtypes(namedType); } }); } @JsonIgnore boolean isNull(); void add(StatsExtension other); void subtract(StatsExtension other); void reset(); StatsExtension clone(); String[] headers(); String byHeader(String header); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/statistics/StatisticsSummary.java
api/src/main/java/io/hyperfoil/api/statistics/StatisticsSummary.java
package io.hyperfoil.api.statistics; import java.io.PrintWriter; import java.util.SortedMap; import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonProperty; public class StatisticsSummary { public final long startTime; public final long endTime; public final long minResponseTime; public final long meanResponseTime; public final long stdDevResponseTime; public final long maxResponseTime; public final SortedMap<Double, Long> percentileResponseTime; // the percentiles depend on configuration public final int requestCount; public final int responseCount; public final int invalid; public final int connectionErrors; public final int requestTimeouts; public final int internalErrors; public final long blockedTime; public final SortedMap<String, StatsExtension> extensions; @JsonCreator public StatisticsSummary(@JsonProperty("startTime") long startTime, @JsonProperty("endTime") long endTime, @JsonProperty("minResponseTime") long minResponseTime, @JsonProperty("meanResponseTime") long meanResponseTime, @JsonProperty("stdDevResponseTime") long stdDevResponseTime, @JsonProperty("maxResponseTime") long maxResponseTime, @JsonProperty("percentileResponseTime") SortedMap<Double, Long> percentileResponseTime, @JsonProperty("requestCount") int requestCount, @JsonProperty("responseCount") int responseCount, @JsonProperty("invalid") int invalid, @JsonProperty("connectionErrors") int connectionErrors, @JsonProperty("requestTimeouts") int requestTimeouts, @JsonProperty("internalErrors") int internalErrors, @JsonProperty("blockedTime") long blockedTime, @JsonProperty("extensions") SortedMap<String, StatsExtension> extensions) { this.startTime = startTime; this.endTime = endTime; this.minResponseTime = minResponseTime; this.meanResponseTime = meanResponseTime; this.stdDevResponseTime = stdDevResponseTime; this.maxResponseTime = maxResponseTime; this.percentileResponseTime = percentileResponseTime; this.requestCount = requestCount; this.responseCount = responseCount; this.invalid = invalid; this.connectionErrors = connectionErrors; this.requestTimeouts = requestTimeouts; this.internalErrors = internalErrors; this.blockedTime = blockedTime; this.extensions = extensions; } public static void printHeader(PrintWriter writer, double[] percentiles) { writer.print("Requests,Responses,Mean,StdDev,Min,"); for (double p : percentiles) { writer.print('p'); writer.print(p); writer.print(','); } writer.print("Max,ConnectionErrors,RequestTimeouts,InternalErrors,Invalid,BlockedTime"); } public void printTo(PrintWriter writer, String[] extensionHeaders) { writer.print(requestCount); writer.print(','); writer.print(responseCount); writer.print(','); writer.print(meanResponseTime); writer.print(','); writer.print(stdDevResponseTime); writer.print(','); writer.print(minResponseTime); writer.print(','); for (long prt : percentileResponseTime.values()) { writer.print(prt); writer.print(','); } writer.print(maxResponseTime); writer.print(','); writer.print(connectionErrors); writer.print(','); writer.print(requestTimeouts); writer.print(','); writer.print(internalErrors); writer.print(','); writer.print(invalid); writer.print(','); writer.print(blockedTime); for (String header : extensionHeaders) { writer.print(','); int index = header.indexOf('.'); StatsExtension value = extensions.get(header.substring(0, index)); if (value != null) { writer.print(value.byHeader(header.substring(index + 1))); } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/statistics/StatisticsSnapshot.java
api/src/main/java/io/hyperfoil/api/statistics/StatisticsSnapshot.java
package io.hyperfoil.api.statistics; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import java.util.TreeMap; import java.util.concurrent.TimeUnit; import java.util.stream.DoubleStream; import org.HdrHistogram.Histogram; /** * Non-thread safe mutable set of values. */ public class StatisticsSnapshot implements Serializable { public int sequenceId = -1; public final Histogram histogram = new Histogram(TimeUnit.MINUTES.toNanos(1), 2); public int requestCount; public int responseCount; public int invalid; public int connectionErrors; public int requestTimeouts; public int internalErrors; public long blockedTime; public final Map<String, StatsExtension> extensions = new HashMap<>(); public boolean isEmpty() { return requestCount + responseCount + invalid + connectionErrors + requestTimeouts + internalErrors == 0 && extensions.values().stream().allMatch(StatsExtension::isNull); } public void reset() { histogram.reset(); requestCount = 0; responseCount = 0; invalid = 0; connectionErrors = 0; requestTimeouts = 0; internalErrors = 0; blockedTime = 0; for (StatsExtension value : extensions.values()) { if (value != null) { value.reset(); } } } public StatisticsSnapshot clone() { StatisticsSnapshot copy = new StatisticsSnapshot(); copy.sequenceId = sequenceId; copy.add(this); return copy; } public void add(StatisticsSnapshot other) { histogram.add(other.histogram); requestCount += other.requestCount; responseCount += other.responseCount; invalid += other.invalid; connectionErrors += other.connectionErrors; requestTimeouts += other.requestTimeouts; internalErrors += other.internalErrors; blockedTime += other.blockedTime; for (String key : other.extensions.keySet()) { StatsExtension their = other.extensions.get(key); StatsExtension my = extensions.get(key); if (their == null) { // noop } else if (my == null) { extensions.put(key, their.clone()); } else { my.add(their); } } } public void subtract(StatisticsSnapshot other) { histogram.subtract(other.histogram); requestCount -= other.requestCount; responseCount -= other.responseCount; invalid -= other.invalid; connectionErrors -= other.connectionErrors; requestTimeouts -= other.requestTimeouts; internalErrors -= other.internalErrors; blockedTime -= other.blockedTime; for (String key : other.extensions.keySet()) { StatsExtension their = other.extensions.get(key); StatsExtension my = extensions.get(key); if (their == null) { // noop } else if (my == null) { my = their.clone(); my.reset(); my.subtract(their); extensions.put(key, my); } else { my.subtract(their); } } } public StatisticsSummary summary(double[] percentiles) { TreeMap<Double, Long> percentilesMap = getPercentiles(percentiles); return new StatisticsSummary(histogram.getStartTimeStamp(), histogram.getEndTimeStamp(), histogram.getMinValue(), (long) histogram.getMean(), (long) histogram.getStdDeviation(), histogram.getMaxValue(), percentilesMap, requestCount, responseCount, invalid, connectionErrors, requestTimeouts, internalErrors, blockedTime, new TreeMap<>(extensions)); } public TreeMap<Double, Long> getPercentiles(double[] percentiles) { return DoubleStream.of(percentiles).collect(TreeMap::new, (map, p) -> map.put(p, histogram.getValueAtPercentile(p)), TreeMap::putAll); } public long errors() { return connectionErrors + requestTimeouts + internalErrors; } @Override public String toString() { return "StatisticsSnapshot{" + "sequenceId=" + sequenceId + ", start=" + histogram.getStartTimeStamp() + ", end=" + histogram.getEndTimeStamp() + ", requestCount=" + requestCount + ", responseCount=" + responseCount + ", invalid=" + invalid + ", connectionErrors=" + connectionErrors + ", requestTimeouts=" + requestTimeouts + ", internalErrors=" + internalErrors + ", blockedTime=" + blockedTime + ", extensions=" + extensions + '}'; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/api/statistics/SessionStatistics.java
api/src/main/java/io/hyperfoil/api/statistics/SessionStatistics.java
package io.hyperfoil.api.statistics; import java.util.Arrays; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.session.Session; /** * This instance holds common statistics shared between all {@link Session sessions} (in given phase) driven by the same * executor. */ public class SessionStatistics { private Phase[] phases; private int[] stepIds; private Map<String, Statistics>[] maps; private int size; @SuppressWarnings("unchecked") public SessionStatistics() { phases = new Phase[4]; stepIds = new int[4]; maps = new Map[4]; } public Statistics getOrCreate(Phase phase, int stepId, String name, long startTime) { for (int i = 0; i < size; ++i) { if (stepIds[i] == stepId && phases[i] == phase) { Statistics s = maps[i].get(name); if (s == null) { s = new Statistics(startTime); maps[i].put(name, s); } return s; } } if (size == stepIds.length) { phases = Arrays.copyOf(phases, size * 2); stepIds = Arrays.copyOf(stepIds, size * 2); maps = Arrays.copyOf(maps, size * 2); } phases[size] = phase; stepIds[size] = stepId; Statistics s = new Statistics(startTime); HashMap<String, Statistics> map = new HashMap<>(); map.put(name, s); maps[size] = map; ++size; return s; } public int size() { return size; } public Phase phase(int index) { return phases[index]; } public int step(int index) { return stepIds[index]; } public Map<String, Statistics> stats(int index) { return maps[index]; } public void prune(Phase phase) { int lastGood = size - 1; while (lastGood >= 0 && phases[lastGood] == phase) { lastGood--; } int lastSize = size; for (int i = 0; i < lastSize; ++i) { if (phases[i] == phase) { if (lastGood > i) { phases[i] = phases[lastGood]; stepIds[i] = stepIds[lastGood]; maps[i] = maps[lastGood]; while (lastGood > i && phases[lastGood] == phase) { lastGood--; } } else { phases[i] = null; stepIds[i] = 0; maps[i] = null; } --size; } } } private class It implements Iterator<Statistics> { int i; Iterator<Statistics> it; @Override public boolean hasNext() { if (it != null && it.hasNext()) { return true; } else { while (i < maps.length && maps[i] != null) { it = maps[i].values().iterator(); ++i; if (it.hasNext()) { return true; } } return false; } } @Override public Statistics next() { if (it != null && it.hasNext()) { return it.next(); } else { while (i < maps.length && maps[i] != null) { it = maps[i].values().iterator(); ++i; if (it.hasNext()) { return it.next(); } } throw new NoSuchElementException(); } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/internal/Controller.java
api/src/main/java/io/hyperfoil/internal/Controller.java
package io.hyperfoil.internal; import java.nio.file.Path; import java.nio.file.Paths; /** * This interface should decouple controller implementation (in clustering module) and its uses (e.g. CLI). * The controller should listen on {@link #host()}:{@link #port()} as usual. */ public interface Controller { Path DEFAULT_ROOT_DIR = Paths.get(System.getProperty("java.io.tmpdir"), "hyperfoil"); String DEPLOYER = Properties.get(Properties.DEPLOYER, "ssh"); long DEPLOY_TIMEOUT = Properties.getLong(Properties.DEPLOY_TIMEOUT, 60000); Path ROOT_DIR = Properties.get(Properties.ROOT_DIR, Paths::get, DEFAULT_ROOT_DIR); Path BENCHMARK_DIR = Properties.get(Properties.BENCHMARK_DIR, Paths::get, ROOT_DIR.resolve("benchmark")); Path HOOKS_DIR = ROOT_DIR.resolve("hooks"); Path RUN_DIR = Properties.get(Properties.RUN_DIR, Paths::get, ROOT_DIR.resolve("run")); String host(); int port(); void stop(); interface Factory { Controller start(Path rootDir); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/internal/Properties.java
api/src/main/java/io/hyperfoil/internal/Properties.java
package io.hyperfoil.internal; import java.util.function.Function; public interface Properties { String HYPERFOIL_STACKTRACE = "io.hyperfoil.stacktrace"; String AGENT_DEBUG_PORT = "io.hyperfoil.agent.debug.port"; String AGENT_DEBUG_SUSPEND = "io.hyperfoil.agent.debug.suspend"; String AGENT_JAVA_EXECUTABLE = "io.hyperfoil.agent.java.executable"; String AGENT_NAME = "io.hyperfoil.agent.name"; String BENCHMARK_DIR = "io.hyperfoil.benchmarkdir"; String CONTROLLER_CLUSTER_IP = "io.hyperfoil.controller.cluster.ip"; String CONTROLLER_CLUSTER_PORT = "io.hyperfoil.controller.cluster.port"; String CONTROLLER_EXTERNAL_URI = "io.hyperfoil.controller.external.uri"; String CONTROLLER_HOST = "io.hyperfoil.controller.host"; String CONTROLLER_KEYSTORE_PATH = "io.hyperfoil.controller.keystore.path"; String CONTROLLER_KEYSTORE_PASSWORD = "io.hyperfoil.controller.keystore.password"; String CONTROLLER_PEM_KEYS = "io.hyperfoil.controller.pem.keys"; String CONTROLLER_PEM_CERTS = "io.hyperfoil.controller.pem.certs"; String CONTROLLER_SECURED_VIA_PROXY = "io.hyperfoil.controller.secured.via.proxy"; String CONTROLLER_PASSWORD = "io.hyperfoil.controller.password"; String CONTROLLER_LOG = "io.hyperfoil.controller.log.file"; String CONTROLLER_LOG_LEVEL = "io.hyperfoil.controller.log.level"; String CONTROLLER_PORT = "io.hyperfoil.controller.port"; String CPU_WATCHDOG_PERIOD = "io.hyperfoil.cpu.watchdog.period"; String CPU_WATCHDOG_IDLE_THRESHOLD = "io.hyperfoil.cpu.watchdog.idle.threshold"; String DEPLOYER = "io.hyperfoil.deployer"; String DEPLOY_TIMEOUT = "io.hyperfoil.deploy.timeout"; String DIST_DIR = "io.hyperfoil.distdir"; String JITTER_WATCHDOG_PERIOD = "io.hyperfoil.jitter.watchdog.period"; String JITTER_WATCHDOG_THRESHOLD = "io.hyperfoil.jitter.watchdog.threshold"; String LOG4J2_CONFIGURATION_FILE = "log4j.configurationFile"; String LOAD_DIR = "io.hyperfoil.loaddir"; String MAX_IN_MEMORY_RUNS = "io.hyperfoil.max.in.memory.runs"; String NETTY_TRANSPORT = "io.hyperfoil.netty.transport"; String ROOT_DIR = "io.hyperfoil.rootdir"; String RUN_DIR = "io.hyperfoil.rundir"; String RUN_ID = "io.hyperfoil.runid"; String TRIGGER_URL = "io.hyperfoil.trigger.url"; String CLI_REQUEST_TIMEOUT = "io.hyperfoil.cli.request.timeout"; String GC_CHECK = "io.hyperfoil.gc.check.enabled"; String CLUSTER_JGROUPS_STACK = "io.hyperfoil.cluster.jgroups_stack"; String REPORT_TEMPLATE = "io.hyperfoil.report.template"; static String get(String property, String def) { return get(property, Function.identity(), def); } static long getLong(String property, long def) { return get(property, Long::valueOf, def); } static int getInt(String property, int def) { return get(property, Integer::valueOf, def); } static boolean getBoolean(String property) { return get(property, Boolean::valueOf, false); } static <T> T get(String property, Function<String, T> f, T def) { String value = System.getProperty(property); if (value != null) { return f.apply(value); } value = System.getenv(property.replaceAll("[^a-zA-Z0-9]", "_").toUpperCase()); if (value != null) { return f.apply(value); } return def; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/function/SerializableFunction.java
api/src/main/java/io/hyperfoil/function/SerializableFunction.java
package io.hyperfoil.function; import java.io.Serializable; import java.util.function.Function; public interface SerializableFunction<T, R> extends Serializable, Function<T, R> { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/function/SerializableConsumer.java
api/src/main/java/io/hyperfoil/function/SerializableConsumer.java
package io.hyperfoil.function; import java.io.Serializable; import java.util.function.Consumer; public interface SerializableConsumer<T> extends Serializable, Consumer<T> { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/function/SerializableBiFunction.java
api/src/main/java/io/hyperfoil/function/SerializableBiFunction.java
package io.hyperfoil.function; import java.io.Serializable; import java.util.function.BiFunction; public interface SerializableBiFunction<T1, T2, R> extends Serializable, BiFunction<T1, T2, R> { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/function/SerializableLongUnaryOperator.java
api/src/main/java/io/hyperfoil/function/SerializableLongUnaryOperator.java
package io.hyperfoil.function; import java.io.Serializable; import java.util.function.LongUnaryOperator; public interface SerializableLongUnaryOperator extends LongUnaryOperator, Serializable { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/function/SerializableBiPredicate.java
api/src/main/java/io/hyperfoil/function/SerializableBiPredicate.java
package io.hyperfoil.function; import java.io.Serializable; import java.util.function.BiPredicate; public interface SerializableBiPredicate<A, B> extends BiPredicate<A, B>, Serializable { @Override default SerializableBiPredicate<A, B> negate() { return (a, b) -> !test(a, b); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/function/SerializableToLongFunction.java
api/src/main/java/io/hyperfoil/function/SerializableToLongFunction.java
package io.hyperfoil.function; import java.io.Serializable; import java.util.function.ToLongFunction; public interface SerializableToLongFunction<T> extends ToLongFunction<T>, Serializable { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/function/SerializableToIntFunction.java
api/src/main/java/io/hyperfoil/function/SerializableToIntFunction.java
package io.hyperfoil.function; import java.io.Serializable; import java.util.function.ToIntFunction; public interface SerializableToIntFunction<T> extends ToIntFunction<T>, Serializable { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/function/SerializableSupplier.java
api/src/main/java/io/hyperfoil/function/SerializableSupplier.java
package io.hyperfoil.function; import java.io.Serializable; import java.util.function.Supplier; public interface SerializableSupplier<T> extends Supplier<T>, Serializable { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/function/SerializableIntPredicate.java
api/src/main/java/io/hyperfoil/function/SerializableIntPredicate.java
package io.hyperfoil.function; import java.io.Serializable; import java.util.function.IntPredicate; public interface SerializableIntPredicate extends IntPredicate, Serializable { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/function/SerializableBiConsumer.java
api/src/main/java/io/hyperfoil/function/SerializableBiConsumer.java
package io.hyperfoil.function; import java.io.Serializable; import java.util.function.BiConsumer; public interface SerializableBiConsumer<A, B> extends Serializable, BiConsumer<A, B> { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/function/SerializableLongBinaryOperator.java
api/src/main/java/io/hyperfoil/function/SerializableLongBinaryOperator.java
package io.hyperfoil.function; import java.io.Serializable; import java.util.function.LongBinaryOperator; public interface SerializableLongBinaryOperator extends LongBinaryOperator, Serializable { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/api/src/main/java/io/hyperfoil/function/SerializablePredicate.java
api/src/main/java/io/hyperfoil/function/SerializablePredicate.java
package io.hyperfoil.function; import java.io.Serializable; import java.util.function.Predicate; public interface SerializablePredicate<T> extends Predicate<T>, Serializable { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/plugins/codegen/src/main/java/io/hyperfoil/codegen/OpenapiMojo.java
plugins/codegen/src/main/java/io/hyperfoil/codegen/OpenapiMojo.java
package io.hyperfoil.codegen; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import org.yaml.snakeyaml.Yaml; import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.Modifier; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.ConstructorDeclaration; import com.github.javaparser.ast.body.FieldDeclaration; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.expr.AnnotationExpr; import com.github.javaparser.ast.expr.MarkerAnnotationExpr; import com.github.javaparser.ast.expr.Name; import com.github.javaparser.ast.expr.NameExpr; import com.github.javaparser.ast.expr.NormalAnnotationExpr; import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr; import com.github.javaparser.ast.expr.StringLiteralExpr; import com.github.javaparser.ast.stmt.BlockStmt; @Mojo(name = "codegen", defaultPhase = LifecyclePhase.GENERATE_SOURCES) public class OpenapiMojo extends AbstractMojo { private static final String COMPONENTS_SCHEMAS = "#/components/schemas/"; @Parameter(readonly = true, defaultValue = "${project}") private MavenProject project; @Parameter(defaultValue = "${project.basedir}/src/main/resources/openapi.yaml") private String input; @Parameter(defaultValue = "${project.build.directory}/generated-sources/java") private String output; @Parameter(required = true) private String modelPackage; @Parameter(required = true) private String servicePackage; @Parameter(required = true) private String routerPackage; @Parameter private String defaultDateFormat; @Parameter(defaultValue = "true") private boolean addToCompileRoots; @Override public void execute() throws MojoExecutionException { Yaml yaml = new Yaml(); Map<String, Object> openapi; try (FileInputStream is = new FileInputStream(input)) { openapi = yaml.load(is); } catch (IOException e) { throw new MojoExecutionException("Failed to read " + input, e); } ensureDir(new File(output), "Output directory"); ensureDir(Paths.get(output, modelPackage.split("\\.")).toFile(), "Package directory"); ensureDir(Paths.get(output, servicePackage.split("\\.")).toFile(), "Service directory"); ensureDir(Paths.get(output, routerPackage.split("\\.")).toFile(), "Router directory"); generateServiceAndRouter(openapi); generateModel(openapi); } private void generateServiceAndRouter(Map<String, Object> openapi) throws MojoExecutionException { ArrayList<Operation> operations = new ArrayList<>(); Map<String, Object> paths = descend(openapi, false, "paths"); for (Map.Entry<String, Object> pathEntry : paths.entrySet()) { String path = pathEntry.getKey(); @SuppressWarnings("unchecked") Map<String, Map<String, Object>> methods = (Map<String, Map<String, Object>>) pathEntry.getValue(); for (Map.Entry<String, Map<String, Object>> methodEntry : methods.entrySet()) { String method = methodEntry.getKey(); Map<String, Object> properties = methodEntry.getValue(); String operationId = requireNonNull(properties, "operationId", path + "." + method); ArrayList<Param> params = new ArrayList<>(); Map<String, Object> requestBodyContent = descend(properties, true, "requestBody", "content"); ArrayList<String> consumes = new ArrayList<>(); if (requestBodyContent != null) { consumes.addAll(requestBodyContent.keySet()); } if (consumes.isEmpty()) { consumes.add(""); } ArrayList<String> produces = new ArrayList<>(); Map<String, Map<String, Object>> responses = requireNonNull(properties, "responses", path + "." + method); for (Map<String, Object> response : responses.values()) { @SuppressWarnings("unchecked") Map<String, Object> content = (Map<String, Object>) response.get("content"); if (content != null) { produces.addAll(content.keySet()); } } if (produces.isEmpty()) { produces.add(""); } @SuppressWarnings("unchecked") List<Map<String, Object>> parameters = (List<Map<String, Object>>) properties.get("parameters"); if (parameters != null) { for (Map<String, Object> param : parameters) { String name = requireNonNull(param, "name", path, method, "parameters"); String in = requireNonNull(param, "in", path, method, "parameters"); boolean required = "true".equalsIgnoreCase(String.valueOf(param.get("required"))); Map<String, Object> schema = requireNonNull(param, "schema", path, method, name); Property property = createProperty(path + "." + method + ".", name, schema); Object defaultValue = schema.get("default"); params.add(new Param(property.originalName, property.fieldName, in, property.type, required, defaultValue == null ? null : String.valueOf(defaultValue))); } } for (String consume : consumes) { for (String produce : produces) { operations.add( new Operation(path, method, operationId, consume, produce, consumes.size(), produces.size(), params)); } } } } writeApiService(operations); writeApiRouter(operations); } private void writeApiRouter(ArrayList<Operation> operations) throws MojoExecutionException { CompilationUnit unit = new CompilationUnit(routerPackage); unit.addImport("java.util.Date"); unit.addImport("java.util.List"); unit.addImport("java.util.Map"); unit.addImport("java.util.Collections"); unit.addImport("io.vertx.core.json.Json"); unit.addImport("io.vertx.ext.web.handler.BodyHandler"); unit.addImport("io.vertx.ext.web.Router"); unit.addImport("io.vertx.ext.web.RoutingContext"); unit.addImport("org.apache.logging.log4j.Logger"); unit.addImport("org.apache.logging.log4j.LogManager"); unit.addImport(modelPackage, false, true); unit.addImport(servicePackage + ".ApiService"); ClassOrInterfaceDeclaration clazz = unit.addClass("ApiRouter", Modifier.Keyword.PUBLIC); clazz.addField("ApiService", "service", Modifier.Keyword.PRIVATE, Modifier.Keyword.FINAL); clazz.addField("Logger", "log", Modifier.Keyword.PRIVATE, Modifier.Keyword.STATIC, Modifier.Keyword.FINAL) .getVariable(0).setInitializer("LogManager.getLogger(ApiRouter.class)"); ConstructorDeclaration ctor = clazz.addConstructor(Modifier.Keyword.PUBLIC); BlockStmt ctorBody = ctor.addParameter("ApiService", "service").addParameter("Router", "router").getBody(); ctorBody.addStatement("this.service = service;"); ctorBody.addStatement("router.route().handler(BodyHandler.create(System.getProperty(\"java.io.tmpdir\")));"); ctorBody.addStatement("router.errorHandler(500, ctx -> {\n" + " log.error(\"Error processing {} {}\", ctx.request().method(), ctx.request().uri(), ctx.failure());\n" + " });"); for (Operation operation : operations) { StringBuilder routing = new StringBuilder("router.").append(operation.method).append("(\"") .append(operation.path.replaceAll("\\{", ":").replaceAll("\\}", "")) .append("\")"); if (!operation.consumes.isEmpty()) { routing.append(".consumes(\"").append(operation.consumes).append("\")"); } if (!operation.produces.isEmpty()) { routing.append(".produces(\"").append(operation.produces).append("\")"); } routing.append(".handler(this::").append(operation.name()).append(");"); ctorBody.addStatement(routing.toString()); } for (Operation operation : operations) { MethodDeclaration method = clazz.addMethod(operation.name(), Modifier.Keyword.PRIVATE); method.addParameter("RoutingContext", "ctx"); BlockStmt body = new BlockStmt(); method.setBody(body); StringBuilder invocation = new StringBuilder("service.").append(operation.name()).append("(ctx"); for (Param param : operation.params) { StringBuilder raw = new StringBuilder(); if (param.in.equals("query") && param.type.replaceAll("<.*>", "").equals("List")) { raw.append("List<String> _").append(param.varName).append(" = ") .append(param.in).append("Params(ctx, \"").append(param.originalName).append("\");"); } else { raw.append("String _").append(param.varName).append(" = ") .append(param.in).append("Param(ctx, \"").append(param.originalName).append("\", "); if (param.defaultValue == null) { raw.append("null"); } else { raw.append('"').append(param.defaultValue).append('"'); } raw.append(");"); } body.addStatement(raw.toString()); if (param.required) { body.addStatement("if (_" + param.varName + " == null) {" + "ctx.response().setStatusCode(400).end(\"" + param.in + " parameter '" + param.originalName + "' was not set!\");" + "return; }"); } body.addStatement(new StringBuilder().append(param.type).append(" ").append(param.varName) .append(" = convert(_").append(param.varName).append(", ").append(param.type.replaceAll("<.*>", "")) .append(".class);").toString()); invocation.append(", ").append(param.varName); } invocation.append(");"); body.addStatement(invocation.toString()); } MethodDeclaration pathParam = clazz.addMethod("pathParam", Modifier.Keyword.PRIVATE).setType("String") .addParameter("RoutingContext", "ctx") .addParameter("String", "name") .addParameter("String", "defaultValue"); pathParam.setBody(new BlockStmt().addStatement("return ctx.pathParam(name);")); MethodDeclaration queryParam = clazz.addMethod("queryParam", Modifier.Keyword.PRIVATE).setType("String") .addParameter("RoutingContext", "ctx") .addParameter("String", "name") .addParameter("String", "defaultValue"); BlockStmt queryParamBody = new BlockStmt() .addStatement("List<String> list = ctx.queryParam(name);") .addStatement("if (list == null || list.isEmpty()) return defaultValue;") .addStatement("return list.iterator().next();"); queryParam.setBody(queryParamBody); MethodDeclaration queryParams = clazz.addMethod("queryParams", Modifier.Keyword.PRIVATE).setType("List<String>") .addParameter("RoutingContext", "ctx") .addParameter("String", "name"); BlockStmt queryParamsBody = new BlockStmt() .addStatement("List<String> list = ctx.queryParam(name);") .addStatement("return list;"); queryParams.setBody(queryParamsBody); MethodDeclaration headerParam = clazz.addMethod("headerParam", Modifier.Keyword.PRIVATE).setType("String") .addParameter("RoutingContext", "ctx") .addParameter("String", "name") .addParameter("String", "defaultValue"); headerParam.setBody(new BlockStmt() .addStatement("String value = ctx.request().getHeader(name);") .addStatement("return value == null ? defaultValue : value;")); MethodDeclaration convert = clazz.addMethod("convert"); convert.addAnnotation(new SingleMemberAnnotationExpr(new Name("SuppressWarnings"), new StringLiteralExpr("unchecked"))); convert.addParameter("String", "value").addParameter("Class<T>", "type").addTypeParameter("T").setType("T"); BlockStmt convertBody = new BlockStmt(); convert.setBody(convertBody); convertBody.addStatement("if (type == String.class) return (T) value;"); convertBody.addStatement("if (type == boolean.class) return (T) Boolean.valueOf(value);"); convertBody.addStatement("if (type == int.class) return (T) Integer.valueOf(value);"); convertBody.addStatement( "if (type == List.class) { if (value == null) return (T) Collections.emptyList(); if (value instanceof String) return (T) Collections.singletonList(value); }"); convertBody.addStatement("if (value == null) { if (type == Map.class) return (T) Collections.emptyMap(); return null; }"); convertBody.addStatement("return Json.decodeValue(value, type);"); MethodDeclaration convertList = clazz.addMethod("convert"); convertList .addAnnotation(new SingleMemberAnnotationExpr(new Name("SuppressWarnings"), new StringLiteralExpr("unchecked"))); convertList.addParameter("List<String>", "value").addParameter("Class<T>", "type").addTypeParameter("T").setType("T"); BlockStmt convertListBody = new BlockStmt(); convertList.setBody(convertListBody); convertListBody.addStatement("if (value == null) return (T) Collections.emptyList();"); convertListBody.addStatement("return (T) value;"); writeUnit(unit, routerPackage, "ApiRouter.java"); } private void writeApiService(ArrayList<Operation> operations) throws MojoExecutionException { CompilationUnit unit = new CompilationUnit(servicePackage); unit.addImport(modelPackage, false, true); unit.addImport("io.vertx.ext.web.RoutingContext"); unit.addImport("java.util", false, true); ClassOrInterfaceDeclaration clazz = unit.addClass("ApiService"); clazz.setInterface(true); for (Operation operation : operations) { MethodDeclaration method = clazz.addMethod(operation.name()); method.setBody(null); method.addParameter("RoutingContext", "ctx"); for (Param param : operation.params) { method.addParameter(param.type, param.varName); } } writeUnit(unit, servicePackage, "ApiService.java"); } private void writeUnit(CompilationUnit unit, String pkg, String className) throws MojoExecutionException { Path apiServicePath = Paths.get(output, pkg.split("\\.")).resolve(className); try { Files.write(apiServicePath, unit.toString().getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new MojoExecutionException("Cannot write file " + apiServicePath, e); } } private <T> T requireNonNull(Map<String, Object> map, String key, String... where) throws MojoExecutionException { @SuppressWarnings("unchecked") T value = (T) map.get(key); if (value == null) { throw new MojoExecutionException(String.join(".", where) + " missing '" + key + "'"); } return value; } private void generateModel(Map<String, Object> openapi) throws MojoExecutionException { Map<String, Object> schemas = descend(openapi, false, "components", "schemas"); for (Map.Entry<String, Object> entry : schemas.entrySet()) { @SuppressWarnings("unchecked") Map<String, Object> value = (Map<String, Object>) entry.getValue(); Object type = value.get("type"); if (!"object".equals(type)) { throw new MojoExecutionException(entry.getKey() + " is not of type 'object': " + type); } @SuppressWarnings("unchecked") Map<String, Object> properties = (Map<String, Object>) value.get("properties"); if (properties == null) { throw new MojoExecutionException(entry.getKey() + " does not have defined 'properties'"); } generateType(entry.getKey(), properties); } if (addToCompileRoots) { project.addCompileSourceRoot(output); } } private Map<String, Object> descend(Map<String, Object> root, boolean allowMissing, String... path) throws MojoExecutionException { Map<String, Object> target = root; for (String element : path) { @SuppressWarnings("unchecked") Map<String, Object> value = (Map<String, Object>) target.get(element); if (value == null) { if (allowMissing) { return null; } else { throw new MojoExecutionException("Cannot descend path " + String.join(".", path)); } } target = value; } return target; } private void ensureDir(File file, String description) throws MojoExecutionException { if (file.exists()) { if (!file.isDirectory()) { throw new MojoExecutionException(description + " " + file + " is not a directory."); } } else if (!file.mkdirs()) { throw new MojoExecutionException("Cannot create directory " + file); } } private void generateType(String name, Map<String, Object> propertyMap) throws MojoExecutionException { CompilationUnit unit = new CompilationUnit(modelPackage); unit.addImport("java.util.Date"); unit.addImport("java.util.List"); unit.addImport("com.fasterxml.jackson.annotation.JsonCreator"); unit.addImport("com.fasterxml.jackson.annotation.JsonFormat"); unit.addImport("com.fasterxml.jackson.annotation.JsonInclude"); unit.addImport("com.fasterxml.jackson.annotation.JsonProperty"); ClassOrInterfaceDeclaration clazz = unit.addClass(name, Modifier.Keyword.PUBLIC); List<Property> properties = propertyMap.entrySet().stream() .map(e -> { @SuppressWarnings("unchecked") Map<String, Object> from = (Map<String, Object>) e.getValue(); return createProperty(name, e.getKey(), from); }) .collect(Collectors.toList()); for (Property property : properties) { FieldDeclaration fieldDeclaration = clazz.addField(property.type, property.fieldName, Modifier.Keyword.PUBLIC, Modifier.Keyword.FINAL); property.fieldAnnotations.forEach(fieldDeclaration::addAnnotation); } ConstructorDeclaration ctor = clazz.addConstructor(Modifier.Keyword.PUBLIC); ctor.addAnnotation(new MarkerAnnotationExpr("JsonCreator")); BlockStmt ctorBody = new BlockStmt(); for (Property property : properties) { com.github.javaparser.ast.body.Parameter p = new com.github.javaparser.ast.body.Parameter( StaticJavaParser.parseType(property.type), property.fieldName); p.addAnnotation(new SingleMemberAnnotationExpr(new Name("JsonProperty"), new StringLiteralExpr(property.fieldName))); ctor.addParameter(p); ctorBody.addStatement("this." + property.fieldName + " = " + property.fieldName + ";"); } ctor.setBody(ctorBody); writeUnit(unit, modelPackage, name + ".java"); } private Property createProperty(String name, String propertyName, Map<String, Object> from) { String ref = (String) from.get("$ref"); if (from.get("type") == null && ref == null) { throw fail(name, propertyName, "Either 'type' or '$ref' must be defined."); } if (ref != null) { if (!ref.startsWith(COMPONENTS_SCHEMAS)) { throw fail(name, propertyName, "Invalid reference to " + ref + " (should start with " + COMPONENTS_SCHEMAS + ")"); } return new Property(propertyName, sanitizeProperty(propertyName), ref.substring(COMPONENTS_SCHEMAS.length()), Collections.emptyList()); } String type = (String) from.get("type"); String propertyType; String format = (String) from.get("format"); ArrayList<AnnotationExpr> fieldAnnotations = new ArrayList<>(); switch (type) { case "string": if (format == null) { propertyType = "String"; } else if (format.equals("date-time")) { propertyType = "Date"; if (defaultDateFormat != null) { fieldAnnotations.add(new NormalAnnotationExpr() .addPair("shape", "JsonFormat.Shape.STRING") .addPair("pattern", new StringLiteralExpr(defaultDateFormat)) .setName("JsonFormat")); } } else { throw fail(name, propertyName, "Unknown string format " + format); } break; case "array": @SuppressWarnings("unchecked") Map<String, Object> items = (Map<String, Object>) from.get("items"); if (items == null) { throw fail(name, propertyName, "Missing 'items'"); } Property item = createProperty(name, propertyName + ".items", items); propertyType = "List<" + item.type + ">"; break; case "boolean": propertyType = "boolean"; break; case "integer": case "number": propertyType = format == null ? "int" : format; break; case "object": String externalType = (String) from.get("x-type"); if (externalType == null) { throw fail(name, propertyName, "Nested objects are not supported; use $ref."); } else { propertyType = externalType; break; } default: throw fail(name, propertyName, "Unknown type " + type); } String jsonInclude = (String) from.get("x-json-include"); if (jsonInclude != null) { fieldAnnotations.add( new SingleMemberAnnotationExpr(new Name("JsonInclude"), new NameExpr("JsonInclude.Include." + jsonInclude))); } return new Property(propertyName, sanitizeProperty(propertyName), propertyType, fieldAnnotations); } private String sanitizeProperty(String name) { StringBuilder sb = new StringBuilder(); boolean upperCase = false; for (int i = 0; i < name.length(); ++i) { char c = name.charAt(i); if (Character.isAlphabetic(c) || Character.isDigit(c)) { sb.append(upperCase ? Character.toUpperCase(c) : c); upperCase = false; } else if (c == '-') { upperCase = true; } else { sb.append('_'); upperCase = false; } } return sb.toString(); } private RuntimeException fail(String name, String propertyName, String msg) { return new RuntimeException(new MojoExecutionException(name + "." + propertyName + ": " + msg)); } private static class Property { private final String originalName; private final String fieldName; private final String type; private final List<AnnotationExpr> fieldAnnotations; private Property(String originalName, String fieldName, String type, List<AnnotationExpr> fieldAnnotations) { this.originalName = originalName; this.fieldName = fieldName; this.type = type; this.fieldAnnotations = fieldAnnotations; } } private static class Operation { private final String path; private final String method; private final String operationId; private final String consumes; private final String produces; private final int numConsumes; private final int numProduces; private final List<Param> params; private final String methodName; private Operation(String path, String method, String operationId, String consumes, String produces, int numConsumes, int numProduces, List<Param> params) { this.path = path; this.method = method; this.operationId = operationId; this.consumes = consumes; this.produces = produces; this.numConsumes = numConsumes; this.numProduces = numProduces; this.params = params; this.methodName = operationId + (numConsumes > 1 ? "$" + consumes.replaceAll("[-./*]", "_") : "") + (numProduces > 1 ? "$" + produces.replaceAll("[-./*]", "_") : ""); } public String name() { return methodName; } } private static class Param { private final String originalName; private final String varName; private final String in; private final String type; private final boolean required; private final String defaultValue; private Param(String originalName, String varName, String in, String type, boolean required, String defaultValue) { this.originalName = originalName; this.varName = varName; this.in = in; this.type = type; this.required = required; this.defaultValue = defaultValue; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/plugins/codegen/src/main/java/io/hyperfoil/codegen/SkeletonMojo.java
plugins/codegen/src/main/java/io/hyperfoil/codegen/SkeletonMojo.java
package io.hyperfoil.codegen; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStreamReader; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import java.util.stream.Stream; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.kohsuke.MetaInfServices; import com.github.javaparser.StaticJavaParser; import com.github.javaparser.ast.CompilationUnit; import com.github.javaparser.ast.ImportDeclaration; import com.github.javaparser.ast.Modifier.Keyword; import com.github.javaparser.ast.body.ClassOrInterfaceDeclaration; import com.github.javaparser.ast.body.MethodDeclaration; import com.github.javaparser.ast.expr.ClassExpr; import com.github.javaparser.ast.expr.SingleMemberAnnotationExpr; import com.github.javaparser.ast.expr.StringLiteralExpr; import com.github.javaparser.ast.stmt.BlockStmt; import com.github.javaparser.ast.type.ClassOrInterfaceType; import com.github.javaparser.ast.type.PrimitiveType; import com.github.javaparser.ast.type.ReferenceType; import com.github.javaparser.ast.type.TypeParameter; import com.github.javaparser.ast.type.VoidType; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.RunHook; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.config.StepBuilder; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.processor.RawBytesHandler; import io.hyperfoil.api.session.Action; import io.hyperfoil.http.api.HeaderHandler; import io.hyperfoil.http.api.StatusHandler; @Mojo(name = "skeleton", defaultPhase = LifecyclePhase.GENERATE_SOURCES) public class SkeletonMojo extends AbstractMojo { private static final Map<String, SkeletonType> TYPES = new HashMap<>(); @Parameter(defaultValue = "${project.basedir}/src/main/java") private String output; @Parameter(alias = "package", property = "skeleton.package") private String pkg; @Parameter(property = "skeleton.name") private String name; @Parameter(property = "skeleton.type") private String type; private BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); static { TYPES.put("step", new SkeletonType("Step", Step.class, StepBuilder.class)); TYPES.put("action", new SkeletonType("Action", Action.class, Action.Builder.class)); TYPES.put("requestprocessor", new SkeletonType("Processor", Processor.class, Processor.Builder.class)); TYPES.put("headerhandler", new SkeletonType("HeaderHandler", HeaderHandler.class, HeaderHandler.Builder.class)); TYPES.put("statushandler", new SkeletonType("StatusHandler", StatusHandler.class, StatusHandler.Builder.class)); TYPES.put("rawbyteshandler", new SkeletonType("RawBytesHandler", RawBytesHandler.class, RawBytesHandler.Builder.class)); TYPES.put("hook", new SkeletonType("Hook", RunHook.class, RunHook.Builder.class)); } private String clazzName; private Map<String, Type> genericMapping = Collections.emptyMap(); private CompilationUnit unit; @Override public void execute() throws MojoExecutionException, MojoFailureException { try { pkg = checkPropertyInteractive("Package", pkg); name = checkPropertyInteractive("Name", name); do { type = checkPropertyInteractive("Type (one of " + TYPES.keySet() + ")", type); type = type.toLowerCase(Locale.US); } while (!TYPES.containsKey(type)); } catch (IOException e) { throw new MojoFailureException("Cannot read input parameters", e); } File pkgDir = Paths.get(output).resolve(pkg.replaceAll("\\.", File.separator)).toFile(); if (pkgDir.exists()) { if (!pkgDir.isDirectory()) { throw new MojoFailureException(pkgDir + " is not a directory."); } } else if (!pkgDir.mkdirs()) { throw new MojoExecutionException("Cannot create " + pkgDir); } SkeletonType st = TYPES.get(type); assert st != null; if (st.iface instanceof ParameterizedTypeImpl) { genericMapping = ((ParameterizedTypeImpl) st.iface).arguments; } unit = new CompilationUnit(pkg); unit.addImport(Name.class); unit.addImport(MetaInfServices.class); clazzName = Character.toUpperCase(name.charAt(0)) + name.substring(1) + st.suffix; ClassOrInterfaceDeclaration clazz = unit.addClass(clazzName); setExtendsOrImplements(clazz, st.iface); stubMethods(st.iface, clazz, new HashSet<>()); ClassOrInterfaceDeclaration builder = new ClassOrInterfaceDeclaration(); setExtendsOrImplements(builder, st.builder); builder.addAnnotation(new SingleMemberAnnotationExpr(new com.github.javaparser.ast.expr.Name("MetaInfServices"), new ClassExpr(getClassOrInterfaceType(st.builder)))) .addAnnotation( new SingleMemberAnnotationExpr(new com.github.javaparser.ast.expr.Name("Name"), new StringLiteralExpr(name))); clazz.addMember(builder.setName("Builder").setModifiers(Keyword.PUBLIC, Keyword.STATIC)); stubMethods(st.builder, builder, new HashSet<>()); unit.getImports().sort(Comparator.comparing(ImportDeclaration::toString)); Path javaFile = pkgDir.toPath().resolve(clazzName + ".java"); try { Files.write(javaFile, unit.toString().getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { throw new MojoExecutionException("Cannot write to file " + javaFile, e); } } private void setExtendsOrImplements(ClassOrInterfaceDeclaration clazz, Type supertype) { if (getRaw(supertype).isInterface()) { clazz.addImplementedType(getClassOrInterfaceType(supertype)); } else { clazz.addExtendedType(getClassOrInterfaceType(supertype)); } } private void stubMethods(Type type, ClassOrInterfaceDeclaration clazz, Set<String> implementedMethods) { if (type == null) { return; } Class<?> raw = getRaw(type); if (raw == Object.class) { return; } for (Method m : raw.getDeclaredMethods()) { if (m.isDefault() || m.isSynthetic() || m.isBridge() || Modifier.isStatic(m.getModifiers())) { continue; } else if (!Modifier.isAbstract(m.getModifiers())) { // crude without signature implementedMethods.add(m.getName()); continue; } else if (implementedMethods.contains(m.getName())) { continue; } MethodDeclaration method = clazz.addMethod(m.getName(), Keyword.PUBLIC); if (m.getName().equals("build") && m.getReturnType() != List.class) { method.setType(new ClassOrInterfaceType(null, clazzName)); } else { method.setType(getType(m.getGenericReturnType())); } method.addMarkerAnnotation("Override"); Type[] genericParameterTypes = m.getGenericParameterTypes(); Set<String> paramNames = new HashSet<>(); for (int i = 0; i < genericParameterTypes.length; i++) { Type param = genericParameterTypes[i]; method.addParameter(getType(param), paramName(param, paramNames)); } BlockStmt body = new BlockStmt(); method.setBody(body); if (m.getReturnType() == boolean.class) { body.addStatement("return false;"); } else if (m.getReturnType() == int.class || m.getReturnType() == long.class) { body.addStatement("return 0;"); } else if (m.getReturnType() != void.class) { body.addStatement("return null;"); } implementedMethods.add(m.getName()); } stubMethods(raw.getSuperclass(), clazz, implementedMethods); for (Class<?> iface : raw.getInterfaces()) { stubMethods(iface, clazz, implementedMethods); } } private Class<?> getRaw(Type type) { Class<?> raw; if (type instanceof Class) { raw = (Class<?>) type; } else if (type instanceof ParameterizedType) { raw = (Class<?>) ((ParameterizedType) type).getRawType(); } else { throw new IllegalStateException(); } return raw; } private String paramName(Type param, Set<String> names) { String name; if (param instanceof Class && ((Class) param).isPrimitive()) { name = String.valueOf(param.getTypeName().charAt(0)); } else { String tname = param.getTypeName(); int genericsStart = tname.indexOf('<'); if (genericsStart > 0) { tname = tname.substring(0, genericsStart); } int lastDot = tname.lastIndexOf('.'); int lastDollar = tname.lastIndexOf('$'); if (lastDot > 0 || lastDollar > 0) { tname = tname.substring(Math.max(lastDot, lastDollar) + 1); } name = Character.toLowerCase(tname.charAt(0)) + tname.substring(1); } while (!names.add(name)) { int lastDigit = name.length() - 1; while (lastDigit >= 0 && Character.isDigit(name.charAt(lastDigit))) { --lastDigit; } lastDigit++; if (lastDigit < name.length()) { int suffix = Integer.parseInt(name.substring(lastDigit)); name = name.substring(0, lastDigit) + suffix; } else { name = name + "2"; } } return name; } private ClassOrInterfaceType getClassOrInterfaceType(Type type) { if (type instanceof Class) { ClassOrInterfaceType iface = StaticJavaParser.parseClassOrInterfaceType(type.getTypeName().replaceAll("\\$", ".")); ClassOrInterfaceType parentScope = iface.getScope().orElse(null); if (parentScope != null && Character.isUpperCase(parentScope.getName().asString().charAt(0))) { addImport(parentScope); parentScope.removeScope(); } else { addImport(iface); iface.removeScope(); } return iface; } else if (type instanceof ParameterizedType) { ClassOrInterfaceType iface = StaticJavaParser .parseClassOrInterfaceType(((ParameterizedType) type).getRawType().getTypeName()); addImport(iface); com.github.javaparser.ast.type.Type[] args = Stream.of(((ParameterizedType) type).getActualTypeArguments()) .map(t -> getType(t)).toArray(com.github.javaparser.ast.type.Type[]::new); iface.setTypeArguments(args); return iface.removeScope(); } else { throw new IllegalStateException("Unexpected type " + type); } } private void addImport(ClassOrInterfaceType iface) { if (!iface.getScope().map(ClassOrInterfaceType::asString).orElse("").equals("java.lang")) { unit.addImport(iface.asString()); } } private com.github.javaparser.ast.type.Type getType(Type type) { if (type instanceof Class) { if (((Class<?>) type).isPrimitive()) { if (type == void.class) { return new VoidType(); } PrimitiveType.Primitive primitive = Stream.of(PrimitiveType.Primitive.values()) .filter(p -> p.name().toLowerCase().equals(type.getTypeName())) .findFirst().orElseThrow(() -> new IllegalStateException("No primitive for " + type)); return new PrimitiveType(primitive); } } else if (type instanceof TypeVariable) { String name = ((TypeVariable<?>) type).getName(); Type actual = genericMapping.get(name); if (actual != null) { return getType(actual); } return new TypeParameter(name); } else if (type instanceof WildcardType) { return new com.github.javaparser.ast.type.WildcardType() .setSuperType(getBound(((WildcardType) type).getLowerBounds())) .setExtendedType(getBound(((WildcardType) type).getUpperBounds())); } return getClassOrInterfaceType(type); } private com.github.javaparser.ast.type.ReferenceType getBound(Type[] types) { if (types.length == 0) { return null; } else if (types.length == 1) { return (ReferenceType) getType(types[0]); } else { throw new UnsupportedOperationException(); } } private void addImport(Type type) { if (type instanceof ParameterizedType) { addImport(((ParameterizedType) type).getRawType()); for (Type arg : ((ParameterizedType) type).getActualTypeArguments()) { addImport(arg); } } else { unit.addImport(type.getTypeName()); } } private String checkPropertyInteractive(String name, String value) throws IOException { while (value == null || value.isEmpty()) { System.out.print(name + ": "); System.out.flush(); value = reader.readLine(); } return value; } private static class SkeletonType { private final Type iface; private final Class<?> builder; private final String suffix; private SkeletonType(String suffix, Type iface, Class<?> builder, String... blacklistedMethods) { this.suffix = suffix; this.iface = iface; this.builder = builder; } } private static class ParameterizedTypeImpl implements ParameterizedType { private final Class<?> raw; private final LinkedHashMap<String, Type> arguments; private ParameterizedTypeImpl(Class<?> raw, LinkedHashMap<String, Type> arguments) { this.raw = raw; this.arguments = arguments; } @Override public Type[] getActualTypeArguments() { return arguments.values().toArray(new Type[0]); } @Override public Type getRawType() { return raw; } @Override public Type getOwnerType() { return null; } } private static class MapBuilder<K, V> { private final LinkedHashMap<K, V> map = new LinkedHashMap<>(); public MapBuilder<K, V> add(K key, V value) { map.put(key, value); return this; } public LinkedHashMap<K, V> map() { return map; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/plugins/maven/src/main/java/io/hyperfoil/maven/RunMojo.java
plugins/maven/src/main/java/io/hyperfoil/maven/RunMojo.java
package io.hyperfoil.maven; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.Collections; import java.util.HashMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.LifecyclePhase; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.plugins.annotations.ResolutionScope; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.statistics.StatisticsSnapshot; import io.hyperfoil.core.impl.LocalBenchmarkData; import io.hyperfoil.core.impl.LocalSimulationRunner; import io.hyperfoil.core.parser.BenchmarkParser; import io.hyperfoil.core.parser.ParserException; import io.hyperfoil.http.statistics.HttpStats; import io.hyperfoil.impl.Util; @Mojo(name = "run", defaultPhase = LifecyclePhase.INTEGRATION_TEST, requiresDependencyResolution = ResolutionScope.COMPILE_PLUS_RUNTIME) public class RunMojo extends AbstractMojo { private static final Logger log = LogManager.getLogger(RunMojo.class); @Parameter(required = true, property = "hyperfoil.yaml") private File yaml; @Parameter(defaultValue = "false", property = "hyperfoil.percentiles") private Boolean outputPercentileDistribution; private Benchmark benchmark; @Override public void execute() throws MojoExecutionException, MojoFailureException { log.info("Start running Hyperfoil simulation"); if (!yaml.exists()) throw new MojoExecutionException("yaml not found: " + yaml.toPath()); // TODO: as we're aggregating snapshots for the same stage we're printing the stats only at the end HashMap<String, StatisticsSnapshot> total = new HashMap<>(); try { benchmark = buildBenchmark(new FileInputStream(yaml), yaml.toPath()); if (benchmark != null) { // We want to log all stats in the same thread to not break the output layout too much. LocalSimulationRunner runner = new LocalSimulationRunner(benchmark, (phase, stepId, metric, snapshot, ignored) -> { total.computeIfAbsent(phase.name() + "/" + metric, k -> new StatisticsSnapshot()).add(snapshot); }, this::printSessionPoolInfo, null); log.info("Running for {}", benchmark.statisticsCollectionPeriod()); log.info("{} threads", benchmark.defaultThreads()); runner.run(); } } catch (FileNotFoundException e) { log.error("Couldn't find yaml file: " + yaml, e); throw new MojoExecutionException("yaml not found: " + yaml.toPath()); } total.forEach(this::printStats); log.info("Finished running simulation"); } private void printSessionPoolInfo(String phase, int min, int max) { log.info("Phase {} used {} - {} sessions.", phase, min, max); } private Benchmark buildBenchmark(InputStream inputStream, Path path) throws MojoFailureException { if (inputStream == null) log.error("Could not find benchmark configuration"); try { Benchmark benchmark = BenchmarkParser.instance().buildBenchmark(inputStream, new LocalBenchmarkData(path), Collections.emptyMap()); if (benchmark == null) log.info("Failed to parse benchmark configuration"); return benchmark; } catch (ParserException | IOException e) { log.error("Error occurred during parsing", e); throw new MojoFailureException("Error occurred during parsing: " + e.getMessage(), e); } } private void printStats(String phaseAndMetric, StatisticsSnapshot stats) { double durationSeconds = (stats.histogram.getEndTimeStamp() - stats.histogram.getStartTimeStamp()) / 1000d; log.info("{}: ", phaseAndMetric); log.info("{} requests in {} s, ", stats.histogram.getTotalCount(), durationSeconds); log.info(" Avg Stdev Max"); log.info("Latency: {} {} {}", Util.prettyPrintNanosFixed((long) stats.histogram.getMean()), Util.prettyPrintNanosFixed((long) stats.histogram.getStdDeviation()), Util.prettyPrintNanosFixed(stats.histogram.getMaxValue())); log.info("Requests/sec: {}", String.format("%.2f", stats.histogram.getTotalCount() / durationSeconds)); if (outputPercentileDistribution) { final ByteArrayOutputStream baos = new ByteArrayOutputStream(); stats.histogram.outputPercentileDistribution(new PrintStream(baos, true, StandardCharsets.UTF_8), 1000.00); String data = baos.toString(StandardCharsets.UTF_8); log.info("\nPercentile Distribution\n\n{}", data); } if (stats.errors() > 0) { log.info("Socket errors: errors {}, timeouts {}", stats.connectionErrors, stats.requestTimeouts); } HttpStats httpStats = HttpStats.get(stats); if (httpStats.status_4xx + httpStats.status_5xx + httpStats.status_other > 0) { log.info("Non-2xx or 3xx responses: {}", httpStats.status_4xx + httpStats.status_5xx + httpStats.status_other); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/distribution/src/test/java/io/hyperfoil/example/ValidateExampleTest.java
distribution/src/test/java/io/hyperfoil/example/ValidateExampleTest.java
package io.hyperfoil.example; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.fail; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.PrintStream; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Paths; import java.util.Collections; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.Stream; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.BenchmarkBuilder; import io.hyperfoil.api.config.Model; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.config.PhaseBuilder; import io.hyperfoil.api.config.PhaseForkBuilder; import io.hyperfoil.api.config.Scenario; import io.hyperfoil.core.impl.LocalBenchmarkData; import io.hyperfoil.core.parser.BenchmarkParser; import io.hyperfoil.core.parser.ParserException; import io.hyperfoil.core.print.YamlVisitor; import io.hyperfoil.function.SerializableSupplier; import io.hyperfoil.http.config.HttpPluginBuilder; import io.hyperfoil.impl.Util; public class ValidateExampleTest { // parameters source public static Stream<Arguments> exampleFiles() throws IOException { return Files.list(Paths.get("examples")) .filter(p -> p.toString().endsWith(".hf.yaml")) .filter(p -> p.toFile().isFile()) .map(p -> Arguments.of(p.toString())); } private InputStream loadOrFail(String exampleFile) { InputStream stream = getClass().getClassLoader().getResourceAsStream(exampleFile); if (stream == null) { fail("Cannot load file " + exampleFile); } return stream; } @ParameterizedTest @MethodSource("exampleFiles") public void testSerializable(String exampleFile) { try { Benchmark benchmark = BenchmarkParser.instance().buildBenchmark(loadOrFail(exampleFile), new LocalBenchmarkData(Paths.get(exampleFile)), Collections.emptyMap()); assertThat(benchmark.name()) .isEqualTo(exampleFile.replace(".hf.yaml", "").replaceFirst("[^" + File.separatorChar + "]*.", "")); byte[] bytes = Util.serialize(benchmark); assertThat(bytes).isNotNull(); } catch (Exception e) { throw new AssertionError("Failure in " + exampleFile, e); } } @ParameterizedTest @MethodSource("exampleFiles") public void testCopy(String exampleFile) { try { LocalBenchmarkData data = new LocalBenchmarkData(Paths.get(exampleFile)); BenchmarkBuilder original = BenchmarkParser.instance().builder(loadOrFail(exampleFile), data, Collections.emptyMap()); BenchmarkBuilder builder = new BenchmarkBuilder(null, Collections.emptyMap()).data(data); HttpPluginBuilder plugin = builder.addPlugin(HttpPluginBuilder::new); HttpPluginBuilder.httpForTesting(original).forEach(http -> plugin.addHttp(http.copy(plugin))); builder.prepareBuild(); for (PhaseBuilder<?> phase : BenchmarkBuilder.phasesForTesting(original)) { TestingPhaseBuilder copy = new TestingPhaseBuilder(builder); // This triggers the copy copy.readForksFrom(phase); copy.prepareBuild(); copy.build(null, new AtomicInteger()); } } catch (Exception e) { throw new AssertionError("Failure in " + exampleFile, e); } } @ParameterizedTest @MethodSource("exampleFiles") public void testPrint(String exampleFile) throws IOException, ParserException { Benchmark benchmark = BenchmarkParser.instance().buildBenchmark(loadOrFail(exampleFile), new LocalBenchmarkData(Paths.get(exampleFile)), Collections.emptyMap()); ByteArrayOutputStream output = new ByteArrayOutputStream(); try (PrintStream stream = new PrintStream(output, false, StandardCharsets.UTF_8)) { new YamlVisitor(stream, 20).walk(benchmark); } String str = output.toString(StandardCharsets.UTF_8); // We want the common stuff properly named assertThat(str).doesNotContain("<recursion detected>"); assertThat(str).doesNotContain("<lambda>"); } private static class TestingPhaseBuilder extends PhaseBuilder<TestingPhaseBuilder> { protected TestingPhaseBuilder(BenchmarkBuilder builder) { super(builder, "-for-testing-" + ThreadLocalRandom.current().nextLong()); } @Override protected Phase buildPhase(SerializableSupplier<Benchmark> benchmark, int phaseId, int iteration, PhaseForkBuilder f) { Scenario scenario = f.scenario().build(); assert scenario != null; return PhaseBuilder.noop(null, 0, 0, name, 0, null, null, null); } @Override protected Model createModel(int iteration, double weight) { throw new UnsupportedOperationException(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false