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/core/src/main/java/io/hyperfoil/core/util/LongFastUUID.java
core/src/main/java/io/hyperfoil/core/util/LongFastUUID.java
package io.hyperfoil.core.util; import java.util.concurrent.ThreadLocalRandom; /** * Generate UUID based on the following match: [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} */ public class LongFastUUID { private static char[] DIGITS = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' }; private LongFastUUID() { } // Note: ideally we would use Long.fastUUID but that's not accessible in newer JDKs public static String randomUUID() { ThreadLocalRandom random = ThreadLocalRandom.current(); long lsb = random.nextLong(), msb = random.nextLong(); char[] buf = new char[36]; set(msb >>> 32, buf, 0, 8); buf[8] = '-'; set(msb >>> 16, buf, 9, 4); buf[13] = '-'; set(msb, buf, 14, 4); buf[18] = '-'; set(lsb >>> 48, buf, 19, 4); buf[23] = '-'; set(lsb, buf, 24, 12); return new String(buf); } private static void set(long value, char[] buf, int offset, int length) { for (int index = offset + length - 1; index >= offset; --index) { buf[index] = DIGITS[(int) (value & 0xF)]; value >>>= 4; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/util/Watermarks.java
core/src/main/java/io/hyperfoil/core/util/Watermarks.java
package io.hyperfoil.core.util; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class Watermarks { private static final Logger log = LogManager.getLogger(Watermarks.class); // The fields are volatile as these can be read by any thread, // but written only by the event-loop executor thread. protected volatile int used = 0; protected volatile int minUsed; protected volatile int maxUsed; public void incrementUsed() { assert used >= 0; //noinspection NonAtomicOperationOnVolatileField used++; if (used > maxUsed) { maxUsed = (int) (long) used; } } public void decrementUsed() { decrementUsed(1); } public void decrementUsed(int num) { //noinspection NonAtomicOperationOnVolatileField used -= num; if (used < minUsed) { minUsed = (int) (long) used; } assert used >= 0; } public int minUsed() { return minUsed; } public int maxUsed() { return maxUsed; } public void resetStats() { minUsed = used; maxUsed = used; } public int current() { return used; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/util/LowHigh.java
core/src/main/java/io/hyperfoil/core/util/LowHigh.java
package io.hyperfoil.core.util; import java.io.Serializable; public class LowHigh implements Serializable { public int low; public int high; public LowHigh() { this(0, 0); } public LowHigh(int low, int high) { this.low = low; this.high = high; } public static LowHigh sum(LowHigh r1, LowHigh r2) { if (r1 == null) return r2; if (r2 == null) return r1; return new LowHigh(r1.low + r2.low, r1.high + r2.high); } public static LowHigh combine(LowHigh r1, LowHigh r2) { if (r1 == null) return r2; if (r2 == null) return r1; return new LowHigh(Math.min(r1.low, r2.low), Math.max(r1.high, r2.high)); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/util/RandomConcurrentSet.java
core/src/main/java/io/hyperfoil/core/util/RandomConcurrentSet.java
package io.hyperfoil.core.util; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.function.Consumer; /** * Concurrent data structure that returns elements randomly. This is not called 'pool' because we don't * expect to wipe out and overwrite the objects completely after {@link #fetch()}. * The structure is mostly non-blocking, with an exception when it needs to be resized (the blocking part * is quite short there as well, though). * Regular operations (not resizing) should not cause any allocations, too. */ public class RandomConcurrentSet<T> { private final int maxPutLookup; private final int fetchAttempts; private final ReadWriteLock resizeLock = new ReentrantReadWriteLock(); private volatile AtomicReferenceArray<T> fetchArray; private volatile AtomicReferenceArray<T> putArray; private volatile int reserved = 0; public RandomConcurrentSet(int initialCapacity, int maxPutLookup, int fetchAttempts) { this.maxPutLookup = maxPutLookup; this.fetchAttempts = fetchAttempts; fetchArray = putArray = new AtomicReferenceArray<>(initialCapacity); } public RandomConcurrentSet(int initialCapacity) { this(initialCapacity, 16, 16); } /** * @return Random object from the set or null. This object is exclusively owned by the caller now until it is returned. * When null is returned the caller should implement some back-off strategy (such as wait in a way not blocking * the thread) and retry later. */ public T fetch() { ThreadLocalRandom random = ThreadLocalRandom.current(); for (;;) { AtomicReferenceArray<T> fetchArray = this.fetchArray; for (int i = 0; i < fetchAttempts; ++i) { int idx = random.nextInt(fetchArray.length()); T element = fetchArray.get(idx); if (element != null && fetchArray.compareAndSet(idx, element, null)) { return element; } } if (fetchArray != this.fetchArray) { continue; } if (fetchArray != putArray) { Lock lock = resizeLock.readLock(); lock.lock(); try { // we can set putArray to fetchArray any time (when we find the fetchArray too sparse) // because the resizing thread is obliged to move all data from the previous array. this.fetchArray = putArray; } finally { lock.unlock(); } continue; } return null; } } /** * Insert a new object or an object previously returned by {@link #fetch()} to the set. * * @param object Any object. */ public void put(T object) { ThreadLocalRandom random = ThreadLocalRandom.current(); Lock readLock = resizeLock.readLock(); for (;;) { // This read lock makes sure that we don't insert anything to array that's going away readLock.lock(); boolean isLocked = true; try { AtomicReferenceArray<T> putArray = this.putArray; for (int i = 0; i < maxPutLookup; ++i) { int idx = random.nextInt(reserved, putArray.length()); if (putArray.get(idx) == null && putArray.compareAndSet(idx, null, object)) { return; } } readLock.unlock(); Lock writeLock = resizeLock.writeLock(); AtomicReferenceArray<T> fetchArray; writeLock.lock(); try { if (putArray != this.putArray) { // If the array has been resized by another thread just retry isLocked = false; continue; } // It is not possible that other thread would be still moving data to the new array since it does // not release read lock until it has moved everything. fetchArray = this.fetchArray; assert fetchArray == putArray; // We'll reserve space for elements from fetchArray; once we'll release the write lock the other threads // still won't write before this limit reserved = putArray.length() + 1; this.putArray = putArray = new AtomicReferenceArray<>(putArray.length() * 2); // this downgrades write lock to read lock readLock.lock(); } finally { writeLock.unlock(); } putArray.set(0, object); int writeIdx = 1; for (int i = 0; i < fetchArray.length(); ++i) { T element = fetchArray.get(i); if (element != null && fetchArray.compareAndSet(i, element, null)) { for (; writeIdx < putArray.length(); ++writeIdx) { if (putArray.compareAndSet(writeIdx, null, element)) { break; } } } } // Now that we have copied all data from fetchArray other threads can insert data to any position this.fetchArray = putArray; reserved = 0; return; } finally { if (isLocked) { readLock.unlock(); } } } } // debug only, not thread-safe! void readAll(Consumer<T> consumer) { for (int i = 0; i < putArray.length(); ++i) { T element = putArray.get(i); if (element != null) { consumer.accept(element); } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/util/Unique.java
core/src/main/java/io/hyperfoil/core/util/Unique.java
package io.hyperfoil.core.util; import java.io.Serializable; public final class Unique implements Serializable { private final boolean sequenceScoped; public Unique() { this(false); } public Unique(boolean sequenceScoped) { this.sequenceScoped = sequenceScoped; } public boolean isSequenceScoped() { return sequenceScoped; } @Override public String toString() { return String.format("%s@%08x", (sequenceScoped ? "<unique[]>" : "<unique>"), System.identityHashCode(this)); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/util/BitSetResource.java
core/src/main/java/io/hyperfoil/core/util/BitSetResource.java
package io.hyperfoil.core.util; import java.util.BitSet; import io.hyperfoil.api.session.Session; public interface BitSetResource extends Session.Resource { void set(int index); boolean get(int index); void clear(int index); static BitSetResource with(int nbits) { if (nbits == 0 || nbits == 1) { class SingleBitSetResource implements BitSetResource { private boolean set; @Override public void set(int index) { validateBitIndex(index); set = true; } private static void validateBitIndex(int index) { if (index != 0) { throw new IndexOutOfBoundsException(); } } @Override public boolean get(int index) { validateBitIndex(index); return set; } @Override public void clear(int index) { validateBitIndex(index); set = false; } } return new SingleBitSetResource(); } class MultiBitSetResource extends BitSet implements BitSetResource { private final int nBits; MultiBitSetResource(int nbits) { super(nbits); this.nBits = nbits; } @Override public void set(final int bitIndex) { validateBitIndex(bitIndex); super.set(bitIndex); } private void validateBitIndex(int bitIndex) { if (bitIndex >= nBits) { throw new IndexOutOfBoundsException(); } } @Override public boolean get(final int bitIndex) { validateBitIndex(bitIndex); return super.get(bitIndex); } @Override public void clear(final int bitIndex) { validateBitIndex(bitIndex); super.clear(bitIndex); } } return new MultiBitSetResource(nbits); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/util/DoubleIncrementBuilder.java
core/src/main/java/io/hyperfoil/core/util/DoubleIncrementBuilder.java
package io.hyperfoil.core.util; import java.util.function.BiConsumer; public class DoubleIncrementBuilder { private final BiConsumer<Double, Double> consumer; private double base; private double increment; public DoubleIncrementBuilder(BiConsumer<Double, Double> consumer) { this.consumer = consumer; } /** * Base value used for first iteration. * * @param base Value. * @return Self. */ public DoubleIncrementBuilder base(double base) { this.base = base; return this; } /** * Value by which the base value is incremented for each (but the very first) iteration. * * @param increment Increment value. * @return Self. */ public DoubleIncrementBuilder increment(double increment) { this.increment = increment; return this; } public void apply() { consumer.accept(base, increment); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/util/Trie.java
core/src/main/java/io/hyperfoil/core/util/Trie.java
package io.hyperfoil.core.util; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.TreeMap; import java.util.stream.Collectors; import java.util.stream.Stream; import io.hyperfoil.api.config.Visitor; public class Trie implements Serializable { @Visitor.Invoke(method = "terms") private final Node[] firstNodes; public Trie(String... strings) { firstNodes = getNodes(Stream.of(strings).map(s -> s.getBytes(StandardCharsets.UTF_8)).collect(Collectors.toList()), 0); } public Map<String, Integer> terms() { TreeMap<String, Integer> map = new TreeMap<>(); for (Node n : firstNodes) { n.writeTo(map, new byte[0]); } return map; } private Node[] getNodes(List<byte[]> strings, int index) { // Quick and dirty impl... Set<Byte> bytes = strings.stream().filter(Objects::nonNull).map(s -> s[index]).collect(Collectors.toSet()); List<Node> nodes = new ArrayList<>(); for (byte b : bytes) { List<byte[]> matching = new ArrayList<>(); int terminal = -1; for (int i = 0; i < strings.size(); i++) { byte[] s = strings.get(i); if (s != null && s[index] == b) { if (s.length == index + 1) { assert terminal < 0 : "Duplicate strings"; terminal = i; } else { matching.add(s); } } else { // to keep terminal indices matching.add(null); } } nodes.add(new Node(b, terminal, getNodes(matching, index + 1))); } return nodes.isEmpty() ? null : nodes.toArray(new Node[0]); } public State newState() { return new State(); } public class State { Node[] current = firstNodes; public int next(byte b) { if (current == null) { // prefix does not match, ignore return -1; } for (Node n : current) { if (n.b == b) { current = n.nextNodes; return n.terminal; } } // no match current = null; return -1; } public void reset() { current = firstNodes; } } private static class Node implements Serializable { final byte b; final int terminal; final Node[] nextNodes; private Node(byte b, int terminal, Node[] nextNodes) { this.b = b; this.terminal = terminal; this.nextNodes = nextNodes; } public void writeTo(Map<String, Integer> map, byte[] prefix) { byte[] current = Arrays.copyOf(prefix, prefix.length + 1); current[prefix.length] = b; if (terminal >= 0) { map.put(new String(current, StandardCharsets.UTF_8), terminal); } if (nextNodes != null) { for (Node n : nextNodes) { n.writeTo(map, current); } } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/print/YamlVisitor.java
core/src/main/java/io/hyperfoil/core/print/YamlVisitor.java
package io.hyperfoil.core.print; import java.io.PrintStream; import java.lang.invoke.SerializedLambda; import java.lang.reflect.Array; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.nio.charset.StandardCharsets; import java.util.Collection; import java.util.Map; import java.util.Stack; import java.util.stream.Stream; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.config.Scenario; import io.hyperfoil.api.config.Sequence; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.config.Visitor; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.processor.Transformer; import io.hyperfoil.api.session.Action; import io.hyperfoil.impl.ReflectionAcceptor; public class YamlVisitor implements Visitor { private static final Class<?> BYTE_ARRAY = byte[].class; private static final Class<?> CHAR_ARRAY = char[].class; private int maxCollectionSize = 20; private int indent = 0; private boolean skipIndent = false; private boolean addLine = false; private final PrintStream stream; private Stack<Object> path = new Stack<>(); public YamlVisitor(PrintStream stream, int maxCollectionSize) { this.stream = stream; this.maxCollectionSize = maxCollectionSize; } public void walk(Benchmark benchmark) { ReflectionAcceptor.accept(benchmark, this); } @Override public boolean visit(String name, Object value, Type fieldType) { if (value == null) { return false; } if (addLine) { stream.println(); addLine = false; } if (skipIndent) { skipIndent = false; } else { printIndent(); } if (name.contains(":")) { stream.print('"'); stream.print(name.replaceAll("\"", "\\\"")); stream.print('"'); } else { stream.print(name); } stream.print(": "); if (path.contains(value)) { stream.println("<recursion detected>"); return true; } else { path.push(value); } try { printValue(value, false, fieldType); } finally { path.pop(); } return true; } protected void printValue(Object value, boolean isList, Type fieldType) { if (ReflectionAcceptor.isScalar(value)) { printMultiline(String.valueOf(value)); return; } Class<?> cls = value.getClass(); if (cls.isArray()) { if (BYTE_ARRAY.isInstance(value)) { printMultiline(new String((byte[]) value, StandardCharsets.UTF_8)); } else if (CHAR_ARRAY.isInstance(value)) { printMultiline(String.valueOf((char[]) value)); } else { printArray(value, cls); } } else if (Collection.class.isAssignableFrom(cls)) { printCollection(fieldType, (Collection<?>) value); } else if (Map.class.isAssignableFrom(cls)) { printMap(fieldType, (Map<?, ?>) value); } else if (Sequence.class.isAssignableFrom(cls)) { printSequence((Sequence) value); } else if (Phase.class.isAssignableFrom(cls)) { printPhase((Phase) value, cls); } else if (Scenario.class.isAssignableFrom(cls)) { printScenario((Scenario) value); } else { boolean onlyImpl = isOnlyImpl(fieldType, cls); if (!onlyImpl) { indent += 2; if (!isList) { stream.println(); printIndent(); } stream.print(getName(value, cls)); stream.print(": "); addLine = true; skipIndent = false; } if (!isList) { indent += 2; addLine = true; skipIndent = false; } if (ReflectionAcceptor.accept(value, this) == 0) { stream.println("{}"); addLine = false; } if (!onlyImpl) { indent -= 2; } if (!isList) { indent -= 2; } } } private void printMultiline(String s) { if (!s.contains("\n")) { stream.println(s); return; } stream.println("|+"); indent += 2; for (String line : s.split("\n")) { printIndent(); stream.println(line); } indent -= 2; } private void printArray(Object value, Class<?> cls) { int length = Array.getLength(value); if (length == 0) { stream.println("[]"); } else { stream.println(); if (length > maxCollectionSize) { printIndent(); stream.printf("# Array has %d elements, printing first %d...%n", length, maxCollectionSize); } for (int i = 0; i < Math.min(length, maxCollectionSize); ++i) { printItem(Array.get(value, i), cls.getComponentType()); } if (length > maxCollectionSize) { printIndent(); stream.printf("# ... another %d/%d elements were truncated.%n", length - maxCollectionSize, length); } } } private void printCollection(Type fieldType, Collection<?> collection) { Type itemType = Object.class; if (fieldType instanceof ParameterizedType && Collection.class.isAssignableFrom((Class<?>) ((ParameterizedType) fieldType).getRawType())) { Type[] types = ((ParameterizedType) fieldType).getActualTypeArguments(); // this won't work with some strange hierarchy of maps if (types.length >= 1) { itemType = types[0]; } } if (collection.isEmpty()) { stream.println("[]"); } else { int size = collection.size(); stream.println(); if (size > maxCollectionSize) { printIndent(); stream.printf("# Collection has %d elements, printing first %d...%n", size, maxCollectionSize); } int counter = 0; for (Object item : collection) { printItem(item, itemType); if (counter++ >= maxCollectionSize) { break; } } if (size > maxCollectionSize) { printIndent(); stream.printf("# ... another %d/%d elements were truncated.%n", size - maxCollectionSize, size); } } } private void printMap(Type fieldType, Map<?, ?> map) { Type valueType = Object.class; if (fieldType instanceof ParameterizedType && Map.class.isAssignableFrom((Class<?>) ((ParameterizedType) fieldType).getRawType())) { Type[] types = ((ParameterizedType) fieldType).getActualTypeArguments(); // this won't work with some strange hierarchy of maps if (types.length >= 2) { valueType = types[1]; } } if (map.isEmpty()) { stream.println("{}"); } else { stream.println(); indent += 2; for (Map.Entry<?, ?> entry : map.entrySet()) { visit(String.valueOf(entry.getKey()), entry.getValue(), valueType); } indent -= 2; } } private void printSequence(Sequence seq) { stream.print(seq.name()); if (seq.concurrency() > 0) { stream.printf("[%d]", seq.concurrency()); } stream.println(": "); for (Step step : seq.steps()) { printItem(step, Step.class); } } private void printPhase(Phase phase, Class<?> cls) { stream.print(phase.name); stream.println(": "); indent += 2; printIndent(); stream.print(getName(phase, cls)); stream.println(": "); skipIndent = false; indent += 2; ReflectionAcceptor.accept(phase, this); indent -= 4; } private void printScenario(Scenario scenario) { stream.println(); indent += 2; printIndent(); stream.println("initialSequences:"); for (Sequence s : scenario.initialSequences()) { printItem(s, Sequence.class); } printIndent(); stream.println("sequences:"); Stream.of(scenario.sequences()) .filter(s -> Stream.of(scenario.initialSequences()).noneMatch(s2 -> s == s2)) .forEach(s -> printItem(s, Sequence.class)); indent -= 2; } private String getName(Object value, Class<?> cls) { String suffix = Stream.of(Step.class, Action.class, Processor.class, Transformer.class) .filter(c -> c.isAssignableFrom(cls)).map(Class::getSimpleName).findFirst().orElse(null); Class<?> clazz = value.getClass(); String name = clazz.getSimpleName(); if (clazz.isSynthetic()) { return lambdaName(value, clazz); } else if (suffix != null && name.endsWith(suffix)) { return Character.toLowerCase(name.charAt(0)) + name.substring(1, name.length() - suffix.length()); } else if (clazz.isAnonymousClass()) { return anonymousName(clazz); } else if (name.isEmpty()) { // shouldn't happen return "(empty:" + clazz.getName() + ")"; } else { return Character.toLowerCase(name.charAt(0)) + name.substring(1); } } private String anonymousName(Class<?> clazz) { Method method = clazz.getEnclosingMethod(); if (method != null) { return clazz.getEnclosingClass().getSimpleName() + "." + method.getName() + "::(anonymous)"; } Constructor<?> ctor = clazz.getEnclosingConstructor(); if (ctor != null) { return clazz.getEnclosingClass().getSimpleName() + ".<init>::(anonymous)"; } return clazz.getEnclosingClass().getSimpleName() + "::(anonymous)"; } private boolean isOnlyImpl(Type fieldType, Class<?> cls) { if (fieldType == cls) { return true; } else if (fieldType instanceof ParameterizedType) { return ((ParameterizedType) fieldType).getRawType() == cls; } else { return false; } } private String lambdaName(Object value, Class<?> cls) { try { Method writeReplace = cls.getDeclaredMethod("writeReplace"); writeReplace.setAccessible(true); SerializedLambda serializedLambda = (SerializedLambda) writeReplace.invoke(value); String implClass = serializedLambda.getImplClass(); String methodName = serializedLambda.getImplMethodName(); if (methodName.startsWith("lambda$")) { methodName = "(lambda)"; } return implClass.substring(implClass.lastIndexOf('/') + 1) + "::" + methodName; } catch (NoSuchMethodException | IllegalAccessException | InvocationTargetException e) { return "(lambda)"; } } private void printIndent() { for (int i = 0; i < indent; ++i) { stream.print(' '); } } private void printItem(Object item, Type fieldType) { if (item == null) { return; } printIndent(); stream.print("- "); skipIndent = true; indent += 2; printValue(item, true, fieldType); indent -= 2; skipIndent = false; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/hooks/ExecRunHook.java
core/src/main/java/io/hyperfoil/core/hooks/ExecRunHook.java
package io.hyperfoil.core.hooks; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.Map; import java.util.function.Consumer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.RunHook; public class ExecRunHook extends RunHook { private static final Logger log = LogManager.getLogger(ExecRunHook.class); private final String command; public ExecRunHook(String name, String command) { super(name); this.command = command; } @Override public boolean run(Map<String, String> properties, Consumer<String> outputConsumer) { ProcessBuilder pb = new ProcessBuilder("sh", "-c", command).inheritIO() .redirectOutput(ProcessBuilder.Redirect.PIPE); pb.environment().putAll(properties); try { log.info("{}: Starting command {}", name, command); Process process = pb.start(); try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) { String line; while ((line = reader.readLine()) != null) { log.trace(line); outputConsumer.accept(line); outputConsumer.accept("\n"); } } int exitValue = process.waitFor(); log.info("{}: Completed command with exit code {}", name, exitValue); return exitValue == 0; } catch (IOException e) { log.error("Cannot start {}", name, e); return false; } catch (InterruptedException e) { log.error("Interrupted during hook execution", e); return false; } } /** * Executes provided command in shell. You can use these environment variables: * <ul> * <li>RUN_ID * <li>RUN_DIR * <li>RUN_DESCRIPTION * <li>BENCHMARK * <li>BENCHMARK_PATH * </ul> */ @MetaInfServices(RunHook.Builder.class) @Name("exec") public static class Builder implements RunHook.Builder, InitFromParam<Builder> { private String cmd; /** * @param param Command to run in shell. * @return Self. */ @Override public Builder init(String param) { this.cmd = param; return this; } @Override public RunHook build(String name) { return new ExecRunHook(name, cmd); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/ProvidedBenchmarkData.java
core/src/main/java/io/hyperfoil/core/impl/ProvidedBenchmarkData.java
package io.hyperfoil.core.impl; import java.io.ByteArrayInputStream; import java.io.InputStream; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import io.hyperfoil.api.config.BenchmarkData; public class ProvidedBenchmarkData implements BenchmarkData { public final Set<String> ignoredFiles = new HashSet<>(); public final Map<String, byte[]> files = new HashMap<>(); public ProvidedBenchmarkData() { } public ProvidedBenchmarkData(Map<String, byte[]> files) { this.files.putAll(files); } @Override public InputStream readFile(String file) { if (ignoredFiles.contains(file) || ignoredFiles.contains(BenchmarkData.sanitize(file))) { return ByteArrayInputStream.nullInputStream(); } byte[] bytes = files.get(file); if (bytes != null) { return new ByteArrayInputStream(bytes); } throw new MissingFileException(file); } @Override public Map<String, byte[]> files() { return files; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/ConnectionStatsConsumer.java
core/src/main/java/io/hyperfoil/core/impl/ConnectionStatsConsumer.java
package io.hyperfoil.core.impl; public interface ConnectionStatsConsumer { void accept(String authority, String tag, int min, int max); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/PhaseInstanceImpl.java
core/src/main/java/io/hyperfoil/core/impl/PhaseInstanceImpl.java
package io.hyperfoil.core.impl; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.collection.ElasticPool; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Model; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.session.PhaseChangeHandler; import io.hyperfoil.api.session.PhaseInstance; import io.hyperfoil.api.session.Session; import io.netty.util.concurrent.EventExecutorGroup; public abstract class PhaseInstanceImpl implements PhaseInstance { protected static final Logger log = LogManager.getLogger(PhaseInstanceImpl.class); protected static final boolean trace = log.isTraceEnabled(); private static final Map<Class<? extends Model>, PhaseCtor> constructors = new HashMap<>(); protected final Phase def; private final String runId; private final int agentId; private final int agentThreads; private final int agentFirstThreadId; protected ElasticPool<Session> sessionPool; protected List<Session> sessionList; private PhaseChangeHandler phaseChangeHandler; // Reads are done without locks protected volatile Status status = Status.NOT_STARTED; // in milliseconds protected long absoluteStartTime; protected String absoluteStartTimeString; protected AtomicInteger activeSessions = new AtomicInteger(0); private volatile Throwable error; private volatile boolean sessionLimitExceeded; private Runnable failedSessionAcquisitionAction; public static PhaseInstance newInstance(Phase def, String runId, int agentId) { PhaseCtor ctor = constructors.get(def.model.getClass()); if (ctor == null) throw new BenchmarkDefinitionException("Unknown phase type: " + def.model); return ctor.create(def, runId, agentId); } interface PhaseCtor { PhaseInstance create(Phase phase, String runId, int agentId); } static { constructors.put(Model.AtOnce.class, AtOnce::new); constructors.put(Model.Always.class, Always::new); constructors.put(Model.RampRate.class, OpenModel::rampRate); constructors.put(Model.ConstantRate.class, OpenModel::constantRate); constructors.put(Model.Sequentially.class, Sequentially::new); //noinspection StaticInitializerReferencesSubClass constructors.put(Model.Noop.class, Noop::new); } protected PhaseInstanceImpl(Phase def, String runId, int agentId) { this.def = def; this.runId = runId; this.agentId = agentId; this.agentThreads = def.benchmark().threads(agentId); this.agentFirstThreadId = IntStream.range(0, agentId).map(id -> def.benchmark().threads(id)).sum(); } @Override public Phase definition() { return def; } @Override public Status status() { return status; } @Override public long absoluteStartTime() { return absoluteStartTime; } @Override public String absoluteStartTimeAsString() { return absoluteStartTimeString; } @Override public void start(EventExecutorGroup executorGroup) { synchronized (this) { assert status == Status.NOT_STARTED : "Status is " + status; status = Status.RUNNING; } recordAbsoluteStartTime(); log.debug("{} changing status to RUNNING", def.name); phaseChangeHandler.onChange(def, Status.RUNNING, false, error) .thenRun(() -> proceedOnStarted(executorGroup)); } /** * This method is called when the phase is started and the status is set to RUNNING.<br> * It should be overridden by the subclasses to handle the very first call to {@link #proceed(EventExecutorGroup)}. */ protected void proceedOnStarted(EventExecutorGroup executorGroup) { proceed(executorGroup); } /** * This method can be overridden (but still need to call super) to create additional timestamps * other than {@link #absoluteStartTime}. */ protected void recordAbsoluteStartTime() { absoluteStartTime = System.currentTimeMillis(); absoluteStartTimeString = String.valueOf(absoluteStartTime); } @Override public void finish() { synchronized (this) { if (status == Status.RUNNING) { status = Status.FINISHED; log.debug("{} changing status to FINISHED", def.name); } else { log.debug("{} already in state {}, not finishing", def.name, status); } } phaseChangeHandler.onChange(def, Status.FINISHED, sessionLimitExceeded, null); } @Override public void tryTerminate() { assert status.isFinished(); if (activeSessions.compareAndSet(0, Integer.MIN_VALUE)) { setTerminated(); } else if (sessionList != null && status == Status.TERMINATING) { // We need to force blocked sessions to check the termination status //noinspection SynchronizeOnNonFinalField synchronized (sessionList) { for (int i = 0; i < sessionList.size(); i++) { Session session = sessionList.get(i); if (session.isActive()) { session.proceed(); } } } } } @Override public void terminate() { synchronized (this) { if (status.ordinal() < Status.TERMINATED.ordinal()) { status = Status.TERMINATING; } } log.debug("{} changing status to TERMINATING", def.name); tryTerminate(); } @Override public void runOnFailedSessionAcquisition(final Runnable action) { this.failedSessionAcquisitionAction = action; } // TODO better name @Override public void setComponents(ElasticPool<Session> sessionPool, List<Session> sessionList, PhaseChangeHandler phaseChangeHandler) { this.sessionPool = sessionPool; this.sessionList = sessionList; this.phaseChangeHandler = phaseChangeHandler; } @Override public void notifyFinished(Session session) { if (session != null) { sessionPool.release(session); } int numActive = activeSessions.decrementAndGet(); if (trace) { log.trace("#{} NotifyFinished, {} has {} active sessions", session == null ? -1 : session.uniqueId(), def.name, numActive); } if (numActive < 0) { throw new IllegalStateException(def.name + " has " + numActive + " active sessions"); } if (numActive == 0 && status.isFinished() && activeSessions.compareAndSet(0, Integer.MIN_VALUE)) { setTerminated(); } } @Override public void setTerminated() { synchronized (this) { status = Status.TERMINATED; } log.debug("{} changing status to TERMINATED", def.name); phaseChangeHandler.onChange(def, status, false, error); } @Override public void fail(Throwable error) { this.error = error; terminate(); } @Override public Throwable getError() { return error; } @Override public String runId() { return runId; } @Override public int agentId() { return agentId; } @Override public int agentThreads() { return agentThreads; } @Override public int agentFirstThreadId() { return agentFirstThreadId; } @Override public void setStatsComplete() { // This method is used only for local simulation (in tests) synchronized (this) { if (status != Status.TERMINATED) { throw new IllegalStateException(); } status = Status.STATS_COMPLETE; } log.debug("{} changing status to STATS_COMPLETE", def.name); } /** * @return {@code true} if the new {@link Session} was started, {@code false} otherwise. */ protected boolean startNewSession() { int numActive = activeSessions.incrementAndGet(); if (numActive < 0) { // finished return false; } if (trace) { log.trace("{} has {} active sessions", def.name, numActive); } Session session; try { session = sessionPool.acquire(); } catch (Throwable t) { log.error("Error during session acquisition", t); notifyFinished(null); return false; } if (session == null) { noSessionsAvailable(); return false; } session.start(this); return true; } private void noSessionsAvailable() { if (failedSessionAcquisitionAction != null) { failedSessionAcquisitionAction.run(); } if (!sessionLimitExceeded) { sessionLimitExceeded = true; } notifyFinished(null); } public static class AtOnce extends PhaseInstanceImpl { private final int users; public AtOnce(Phase def, String runId, int agentId) { super(def, runId, agentId); Model.AtOnce model = (Model.AtOnce) def.model; if (model.users > 0) { this.users = def.benchmark().slice(model.users, agentId); } else if (model.usersPerAgent > 0) { this.users = model.usersPerAgent; } else if (model.usersPerThread > 0) { this.users = model.usersPerThread * def.benchmark().threads(agentId); } else { this.users = 0; } } @Override public void proceed(EventExecutorGroup executorGroup) { assert activeSessions.get() == 0; for (int i = 0; i < users; ++i) { startNewSession(); } } @Override public void reserveSessions() { if (users > 0) { sessionPool.reserve(users); } } } public static class Always extends PhaseInstanceImpl { final int users; public Always(Phase def, String runId, int agentId) { super(def, runId, agentId); Model.Always model = (Model.Always) def.model; if (model.users > 0) { users = def.benchmark().slice(model.users, agentId); } else if (model.usersPerAgent > 0) { users = model.usersPerAgent; } else if (model.usersPerThread > 0) { users = model.usersPerThread * def.benchmark().threads(agentId); } else { users = 0; } } @Override public void proceed(EventExecutorGroup executorGroup) { assert activeSessions.get() == 0; for (int i = 0; i < users; ++i) { startNewSession(); } } @Override public void reserveSessions() { if (users > 0) { sessionPool.reserve(users); } } @Override public void notifyFinished(Session session) { if (status.isFinished() || session == null) { super.notifyFinished(session); } else { session.start(this); } } } public static class Sequentially extends PhaseInstanceImpl { private int counter = 0; public Sequentially(Phase def, String runId, int agentId) { super(def, runId, agentId); } @Override public void proceed(EventExecutorGroup executorGroup) { assert activeSessions.get() == 0; startNewSession(); } @Override public void reserveSessions() { sessionPool.reserve(1); } @Override public void notifyFinished(Session session) { Model.Sequentially model = (Model.Sequentially) def.model; if (++counter >= model.repeats) { synchronized (this) { if (status.ordinal() < Status.TERMINATING.ordinal()) { status = Status.TERMINATING; log.debug("{} changing status to TERMINATING", def.name); } else { log.warn("{} not terminating because it is already {}", def.name, status); } } super.notifyFinished(session); } else { session.start(this); } } } public static class Noop extends PhaseInstanceImpl { protected Noop(Phase def, String runId, int agentId) { super(def, runId, agentId); } @Override public void proceed(EventExecutorGroup executorGroup) { } @Override public void reserveSessions() { } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/SimulationRunner.java
core/src/main/java/io/hyperfoil/core/impl/SimulationRunner.java
package io.hyperfoil.core.impl; import java.lang.management.GarbageCollectorMXBean; import java.lang.management.ManagementFactory; import java.text.SimpleDateFormat; import java.time.Clock; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.StreamSupport; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.BenchmarkExecutionException; import io.hyperfoil.api.collection.ElasticPool; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.session.AgentData; import io.hyperfoil.api.session.ControllerListener; import io.hyperfoil.api.session.GlobalData; import io.hyperfoil.api.session.PhaseInstance; import io.hyperfoil.api.session.Session; import io.hyperfoil.api.session.ThreadData; import io.hyperfoil.api.statistics.SessionStatistics; import io.hyperfoil.api.statistics.Statistics; import io.hyperfoil.core.api.Plugin; import io.hyperfoil.core.api.PluginRunData; import io.hyperfoil.core.session.AgentDataImpl; import io.hyperfoil.core.session.GlobalDataImpl; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.core.session.ThreadDataImpl; import io.hyperfoil.core.util.CpuWatchdog; import io.hyperfoil.impl.Util; import io.hyperfoil.internal.Properties; import io.netty.channel.EventLoop; import io.netty.channel.EventLoopGroup; import io.vertx.core.AsyncResult; import io.vertx.core.CompositeFuture; import io.vertx.core.Future; import io.vertx.core.Handler; /** * @author <a href="mailto:julien@julienviet.com">Julien Viet</a> * @author <a href="mailto:johara@redhat.com">John O'Hara</a> */ public class SimulationRunner { protected static final Logger log = LogManager.getLogger(SimulationRunner.class); private static final Clock DEFAULT_CLOCK = Clock.systemDefaultZone(); protected final Benchmark benchmark; protected final int agentId; protected final String runId; protected final Map<String, PhaseInstance> instances = new HashMap<>(); protected final List<Session> sessions = new ArrayList<>(); private final Map<String, SharedResources> sharedResources = new HashMap<>(); protected final EventLoopGroup eventLoopGroup; protected final EventLoop[] executors; private final Queue<Phase> toPrune; private final PluginRunData[] runData; private ControllerListener controllerListener; private final Consumer<Throwable> errorHandler; private boolean isDepletedMessageQuietened; private Thread jitterWatchdog; private CpuWatchdog cpuWatchdog; private final GlobalDataImpl[] globalData; private final GlobalDataImpl.Collector globalCollector = new GlobalDataImpl.Collector(); public SimulationRunner(Benchmark benchmark, String runId, int agentId, Consumer<Throwable> errorHandler) { this.eventLoopGroup = EventLoopFactory.INSTANCE.create(benchmark.threads(agentId)); this.executors = StreamSupport.stream(eventLoopGroup.spliterator(), false).map(EventLoop.class::cast) .toArray(EventLoop[]::new); this.benchmark = benchmark; this.runId = runId; this.agentId = agentId; if (benchmark.phases().isEmpty()) { throw new BenchmarkDefinitionException("This benchmark does not have any phases, nothing to do!"); } this.toPrune = new ArrayBlockingQueue<>(benchmark.phases().size()); this.runData = benchmark.plugins().stream() .map(config -> Plugin.lookup(config).createRunData(benchmark, executors, agentId)) .toArray(PluginRunData[]::new); this.errorHandler = errorHandler; this.globalData = Arrays.stream(executors).map(GlobalDataImpl::new).toArray(GlobalDataImpl[]::new); } public void setControllerListener(ControllerListener controllerListener) { this.controllerListener = controllerListener; } public void init() { long initSimulationStartTime = System.currentTimeMillis(); AgentData agentData = new AgentDataImpl(); ThreadData[] threadData = new ThreadData[executors.length]; Arrays.setAll(threadData, executorId -> new ThreadDataImpl()); for (Phase def : benchmark.phases()) { SharedResources sharedResources; if (def.sharedResources == null) { // Noop phases don't use any resources sharedResources = SharedResources.NONE; } else if ((sharedResources = this.sharedResources.get(def.sharedResources)) == null) { sharedResources = new SharedResources(executors.length); List<Session> phaseSessions = sharedResources.sessions = new ArrayList<>(); SessionStatistics[] statistics = sharedResources.statistics; Supplier<Session> sessionSupplier = () -> { Session session; int executorId; synchronized (this.sessions) { // We need to set executor based on the id within phase (shared resources) because // if the connection pool size = number of users we need to match the #sessions in // each executor to the #connections. executorId = phaseSessions.size() % executors.length; session = SessionFactory.create(def.scenario, executorId, this.sessions.size()); this.sessions.add(session); phaseSessions.add(session); } session.attach(executors[executorId], threadData[executorId], agentData, globalData[executorId], statistics[executorId]); for (int i = 0; i < runData.length; ++i) { runData[i].initSession(session, executorId, def.scenario, DEFAULT_CLOCK); } session.reserve(def.scenario); return session; }; sharedResources.sessionPool = new AffinityAwareSessionPool(executors, sessionSupplier); this.sharedResources.put(def.sharedResources, sharedResources); } PhaseInstance phase = PhaseInstanceImpl.newInstance(def, runId, agentId); instances.put(def.name(), phase); phase.setComponents(sharedResources.sessionPool, sharedResources.sessions, this::phaseChanged); phase.runOnFailedSessionAcquisition(() -> { if (!isDepletedMessageQuietened) { log.warn("Pool depleted, throttling execution! Enable trace logging to see subsequent pool depletion messages."); isDepletedMessageQuietened = true; } else { log.trace("Pool depleted, throttling execution!"); } }); phase.reserveSessions(); // at this point all session resources should be reserved } // hint the GC to tenure sessions this.runGC(); jitterWatchdog = new Thread(this::observeJitter, "jitter-watchdog"); jitterWatchdog.setDaemon(true); cpuWatchdog = new CpuWatchdog(errorHandler, () -> instances.values().stream().anyMatch(p -> !p.definition().isWarmup)); cpuWatchdog.start(); log.info("Simulation initialization took {} ms", System.currentTimeMillis() - initSimulationStartTime); } public void openConnections(Function<Callable<Void>, Future<Void>> blockingHandler, Handler<AsyncResult<Void>> handler) { @SuppressWarnings("rawtypes") ArrayList<Future> futures = new ArrayList<>(); for (PluginRunData plugin : runData) { plugin.openConnections(blockingHandler, futures::add); } CompositeFuture composite = CompositeFuture.join(futures); composite.onComplete(result -> { if (result.failed()) { log.error("One of the HTTP client pools failed to start."); } handler.handle(result.mapEmpty()); jitterWatchdog.start(); }); } private void observeJitter() { long period = Properties.getLong(Properties.JITTER_WATCHDOG_PERIOD, 50); long threshold = Properties.getLong(Properties.JITTER_WATCHDOG_THRESHOLD, 100); long lastTimestamp = System.nanoTime(); while (true) { try { Thread.sleep(period); } catch (InterruptedException e) { log.debug("Interrupted, terminating jitter watchdog"); return; } long currentTimestamp = System.nanoTime(); long delay = TimeUnit.NANOSECONDS.toMillis(currentTimestamp - lastTimestamp); if (delay > threshold) { String message = String.format( "%s | Jitter watchdog was not invoked for %d ms (threshold is %d ms); please check your GC settings.", new SimpleDateFormat("HH:mm:ss.SSS").format(new Date()), delay, threshold); log.error(message); errorHandler.accept(new BenchmarkExecutionException(message)); } lastTimestamp = currentTimestamp; } } protected CompletableFuture<Void> phaseChanged(Phase phase, PhaseInstance.Status status, boolean sessionLimitExceeded, Throwable error) { if (!phase.isWarmup) { if (status == PhaseInstance.Status.RUNNING) { cpuWatchdog.notifyPhaseStart(phase.name); } else if (status.isFinished()) { cpuWatchdog.notifyPhaseEnd(phase.name); } } if (status == PhaseInstance.Status.TERMINATED) { return completePhase(phase).whenComplete((nil, e) -> notifyAndScheduleForPruning(phase, status, sessionLimitExceeded, error != null ? error : e, globalCollector.extract())); } else { notifyAndScheduleForPruning(phase, status, sessionLimitExceeded, error, null); return Util.COMPLETED_VOID_FUTURE; } } private CompletableFuture<Void> completePhase(Phase phase) { SharedResources resources = this.sharedResources.get(phase.sharedResources); if (resources == null) { return Util.COMPLETED_VOID_FUTURE; } List<CompletableFuture<Void>> futures = new ArrayList<>(executors.length); long now = System.currentTimeMillis(); for (int i = 0; i < executors.length; ++i) { SessionStatistics statistics = resources.statistics[i]; if (executors[i].inEventLoop()) { if (statistics != null) { applyToPhase(statistics, phase, now, Statistics::end); } globalCollector.collect(phase.name, globalData[i]); } else { CompletableFuture<Void> cf = new CompletableFuture<>(); futures.add(cf); GlobalDataImpl gd = globalData[i]; executors[i].execute(() -> { try { globalCollector.collect(phase.name, gd); if (statistics != null) { applyToPhase(statistics, phase, now, Statistics::end); } cf.complete(null); } catch (Throwable t) { cf.completeExceptionally(t); } }); } } return CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])); } private void notifyAndScheduleForPruning(Phase phase, PhaseInstance.Status status, boolean sessionLimitExceeded, Throwable error, Map<String, GlobalData.Element> globalData) { if (controllerListener != null) { controllerListener.onPhaseChange(phase, status, sessionLimitExceeded, error, globalData); } if (status == PhaseInstance.Status.TERMINATED) { toPrune.add(phase); } } public void shutdown() { if (jitterWatchdog != null) { jitterWatchdog.interrupt(); } if (cpuWatchdog != null) { cpuWatchdog.stop(); } for (PluginRunData plugin : runData) { plugin.shutdown(); } eventLoopGroup.shutdownGracefully(0, 10, TimeUnit.SECONDS); for (Session session : sessions) { SessionFactory.destroy(session); } } public void visitSessions(Consumer<Session> consumer) { synchronized (sessions) { for (int i = 0; i < sessions.size(); i++) { Session session = sessions.get(i); consumer.accept(session); } } } // This method should be invoked only from vert.x event-loop thread public void visitStatistics(Consumer<SessionStatistics> consumer) { for (SharedResources sharedResources : this.sharedResources.values()) { if (sharedResources.currentPhase == null) { // Phase(s) with these resources have not been started yet continue; } for (SessionStatistics statistics : sharedResources.statistics) { consumer.accept(statistics); } } Phase phase; while ((phase = toPrune.poll()) != null) { Phase phase2 = phase; for (SharedResources sharedResources : this.sharedResources.values()) { if (sharedResources.statistics == null) { continue; } SessionStatistics[] sessionStatistics = sharedResources.statistics; for (int i = 0; i < sessionStatistics.length; i++) { SessionStatistics statistics = sessionStatistics[i]; executors[i].execute(() -> statistics.prune(phase2)); } } } } public void visitStatistics(Phase phase, Consumer<SessionStatistics> consumer) { SharedResources sharedResources = this.sharedResources.get(phase.sharedResources); if (sharedResources == null || sharedResources.statistics == null) { return; } for (SessionStatistics statistics : sharedResources.statistics) { consumer.accept(statistics); } } public void visitSessionPoolStats(SessionStatsConsumer consumer) { for (SharedResources sharedResources : this.sharedResources.values()) { if (sharedResources.currentPhase == null) { // Phase(s) with these resources have not been started yet continue; } recordSessionStats(sharedResources.sessionPool, sharedResources.currentPhase.definition().name(), consumer); } } public void visitSessionPoolStats(Phase phase, SessionStatsConsumer consumer) { SharedResources sharedResources = this.sharedResources.get(phase.sharedResources); if (sharedResources != null) { recordSessionStats(sharedResources.sessionPool, phase.name(), consumer); } } private void recordSessionStats(ElasticPool<Session> sessionPool, String phaseName, SessionStatsConsumer consumer) { int minUsed = sessionPool.minUsed(); int maxUsed = sessionPool.maxUsed(); sessionPool.resetStats(); if (minUsed <= maxUsed && maxUsed != 0) { consumer.accept(phaseName, minUsed, maxUsed); } } public void visitConnectionStats(ConnectionStatsConsumer consumer) { for (PluginRunData plugin : runData) { plugin.visitConnectionStats(consumer); } } public void startPhase(String phase) { PhaseInstance phaseInstance = instances.get(phase); SharedResources sharedResources = this.sharedResources.get(phaseInstance.definition().sharedResources); if (sharedResources != null) { // Avoid NPE in noop phases sharedResources.currentPhase = phaseInstance; if (sharedResources.statistics != null) { long now = System.currentTimeMillis(); for (int i = 0; i < executors.length; ++i) { SessionStatistics statistics = sharedResources.statistics[i]; executors[i].execute(() -> applyToPhase(statistics, phaseInstance.definition(), now, Statistics::start)); } } } phaseInstance.start(eventLoopGroup); } private void applyToPhase(SessionStatistics statistics, Phase phase, long now, BiConsumer<Statistics, Long> f) { for (int j = 0; j < statistics.size(); ++j) { if (statistics.phase(j) == phase) { for (Statistics s : statistics.stats(j).values()) { f.accept(s, now); } } } } public void finishPhase(String phase) { instances.get(phase).finish(); } public void tryTerminatePhase(String phase) { instances.get(phase).tryTerminate(); } public void terminatePhase(String phase) { instances.get(phase).terminate(); } public List<String> listConnections() { ArrayList<String> list = new ArrayList<>(); for (PluginRunData plugin : runData) { plugin.listConnections(list::add); } return list; } public String getCpuUsage(String name) { return cpuWatchdog.getCpuUsage(name); } public void addGlobalData(Map<String, GlobalData.Element> globalData) { for (int i = 0; i < executors.length; ++i) { GlobalDataImpl data = this.globalData[i]; executors[i].execute(() -> { data.add(globalData); }); } } /** * It forces the garbage collection process. * If the JVM arg {@link Properties#GC_CHECK} is set, it will also perform an additional check to ensure that the * GC actually occurred. * * <p> * Note: This method uses {@link ManagementFactory#getGarbageCollectorMXBeans()} to gather GC bean information * and checks if at least one GC cycle has completed. It waits for the GC to stabilize within a maximum wait time. * If GC beans are not available, it waits pessimistically for a defined period after invoking {@code System.gc()}. * </p> * * @see #runSystemGC() * @see ManagementFactory#getGarbageCollectorMXBeans() */ private void runGC() { long start = System.currentTimeMillis(); if (!Properties.getBoolean(Properties.GC_CHECK)) { this.runSystemGC(); } else { // Heavily inspired by // https://github.com/openjdk/jmh/blob/6d6ce6315dc39d1d3abd0e3ac9eca9c38f767112/jmh-core/src/main/java/org/openjdk/jmh/runner/BaseRunner.java#L309 log.info("Running additional GC check!"); // Collect GC beans List<GarbageCollectorMXBean> enabledBeans = new ArrayList<>(); long beforeGcCount = 0; for (GarbageCollectorMXBean bean : ManagementFactory.getGarbageCollectorMXBeans()) { long count = bean.getCollectionCount(); if (count != -1) { enabledBeans.add(bean); beforeGcCount += bean.getCollectionCount(); } } // Run the GC this.runSystemGC(); // Make sure the GC actually happened // a) That at least two collections happened, indicating GC work. // b) That counter updates have not happened for a while, indicating GC work had ceased. final int MAX_WAIT_MS = 10 * 1000; if (enabledBeans.isEmpty()) { log.warn("MXBeans can not report GC info. System.gc() invoked, but cannot check whether GC actually happened!"); return; } boolean gcHappened = false; boolean stable = false; long checkStart = System.nanoTime(); while (TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - checkStart) < MAX_WAIT_MS) { long afterGcCount = 0; for (GarbageCollectorMXBean bean : enabledBeans) { afterGcCount += bean.getCollectionCount(); } if (!gcHappened) { if (afterGcCount - beforeGcCount >= 2) { gcHappened = true; } } else { if (afterGcCount == beforeGcCount) { // Stable! stable = true; break; } beforeGcCount = afterGcCount; } try { TimeUnit.MILLISECONDS.sleep(20); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } if (!stable) { if (gcHappened) { log.warn("System.gc() was invoked but unable to wait while GC stopped, is GC too asynchronous?"); } else { log.warn("System.gc() was invoked but couldn't detect a GC occurring, is System.gc() disabled?"); } } } log.info("Overall GC run took {} ms", (System.currentTimeMillis() - start)); } /** * Executes the garbage collector (GC) and forces object finalization before each GC run. * The method runs the garbage collector twice to ensure maximum garbage collection, * and forces finalization of objects before each GC execution. It logs the time taken * to complete the garbage collection process. * * @see System#runFinalization() * @see System#gc() */ private void runSystemGC() { long actualGCRun = System.currentTimeMillis(); // Run the GC twice and force finalization before every GC run System.runFinalization(); System.gc(); System.runFinalization(); System.gc(); log.info("GC execution took {} ms", (System.currentTimeMillis() - actualGCRun)); } private static class SharedResources { static final SharedResources NONE = new SharedResources(0); PhaseInstance currentPhase; ElasticPool<Session> sessionPool; List<Session> sessions; SessionStatistics[] statistics; SharedResources(int executorCount) { statistics = new SessionStatistics[executorCount]; for (int executorId = 0; executorId < executorCount; ++executorId) { this.statistics[executorId] = new SessionStatistics(); } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/LocalBenchmarkData.java
core/src/main/java/io/hyperfoil/core/impl/LocalBenchmarkData.java
package io.hyperfoil.core.impl; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.HashMap; import java.util.Map; import io.hyperfoil.api.config.BenchmarkData; public class LocalBenchmarkData implements BenchmarkData { protected final Path benchmarkPath; protected final Map<String, byte[]> files = new HashMap<>(); public LocalBenchmarkData(Path benchmarkPath) { this.benchmarkPath = benchmarkPath; } @Override public InputStream readFile(String file) { byte[] bytes = files.get(file); if (bytes == null) { Path path = Paths.get(file); if (!path.isAbsolute()) { if (benchmarkPath == null) { throw new MissingFileException(file, "Cannot load relative path " + file, null); } path = benchmarkPath.getParent().resolve(file); } try { bytes = Files.readAllBytes(path); files.put(file, bytes); } catch (IOException e) { throw new MissingFileException(file, "Local file " + file + " (" + path.toAbsolutePath() + ") cannot be read.", e); } } return new ByteArrayInputStream(bytes); } @Override public Map<String, byte[]> files() { return files; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/OpenModel.java
core/src/main/java/io/hyperfoil/core/impl/OpenModel.java
package io.hyperfoil.core.impl; import io.hyperfoil.api.config.Model; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.session.PhaseInstance; import io.hyperfoil.core.impl.rate.RateGenerator; final class OpenModel { public static PhaseInstance constantRate(Phase def, String runId, int agentId) { var model = (Model.ConstantRate) def.model; double usersPerSec = def.benchmark().slice(model.usersPerSec, agentId); if (model.variance) { return new OpenModelPhase(RateGenerator.poissonConstantRate(usersPerSec), def, runId, agentId); } else { return new OpenModelPhase(RateGenerator.constantRate(usersPerSec), def, runId, agentId); } } public static PhaseInstance rampRate(Phase def, String runId, int agentId) { var model = (Model.RampRate) def.model; double initialUsersPerSec = def.benchmark().slice(model.initialUsersPerSec, agentId); double targetUsersPerSec = def.benchmark().slice(model.targetUsersPerSec, agentId); long durationMs = def.duration; if (model.variance) { return new OpenModelPhase(RateGenerator.poissonRampRate(initialUsersPerSec, targetUsersPerSec, durationMs), def, runId, agentId); } else { return new OpenModelPhase(RateGenerator.rampRate(initialUsersPerSec, targetUsersPerSec, durationMs), def, runId, agentId); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/OpenModelPhase.java
core/src/main/java/io/hyperfoil/core/impl/OpenModelPhase.java
package io.hyperfoil.core.impl; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; import io.hyperfoil.api.config.Model; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.impl.rate.FireTimeListener; import io.hyperfoil.core.impl.rate.RateGenerator; import io.netty.util.concurrent.EventExecutorGroup; /** * This is a base class for Open Model phases that need to compensate users based on the available ones in the session pool. * <br> * The notion of being "throttled" users requires some explanation: * <ul> * <li>a user requires a {@link Session} to run, hence the two terms are used to denote the same concept</li> * <li>starting a {@link Session} doesn't mean immediate execution, but scheduling a deferred start in the * {@link Session#executor()}</li> * <li>given that {@link Session}s are pooled, being throttled means that no available instances are found by * {@link #onFireTimes(long)}</li> * <li>when a {@link Session} finishes, {@link #notifyFinished(Session)} can immediately restart it if there are * throttled users, preventing it to be pooled</li> * </ul> * <p> * The last point is crucial because it means that a too small amount of pooled sessions would be "compensated" only * when a session finished, instead of when {@link #sessionPool} has available sessions available. */ final class OpenModelPhase extends PhaseInstanceImpl implements FireTimeListener { private final int maxSessions; private final AtomicLong throttledUsers = new AtomicLong(0); private final RateGenerator rateGenerator; private final long relativeFirstFireTime; OpenModelPhase(RateGenerator rateGenerator, Phase def, String runId, int agentId) { super(def, runId, agentId); this.rateGenerator = rateGenerator; this.maxSessions = Math.max(1, def.benchmark().slice(((Model.OpenModel) def.model).maxSessions, agentId)); this.relativeFirstFireTime = rateGenerator.lastComputedFireTimeMs(); } @Override public void reserveSessions() { if (log.isDebugEnabled()) { log.debug("Phase {} reserving {} sessions", def.name, maxSessions); } sessionPool.reserve(maxSessions); } @Override protected void proceedOnStarted(final EventExecutorGroup executorGroup) { long elapsedMs = System.currentTimeMillis() - absoluteStartTime; long remainingMsToFirstFireTime = relativeFirstFireTime - elapsedMs; if (remainingMsToFirstFireTime > 0) { executorGroup.schedule(() -> proceed(executorGroup), remainingMsToFirstFireTime, TimeUnit.MILLISECONDS); } else { proceed(executorGroup); } } @Override public void proceed(final EventExecutorGroup executorGroup) { if (status.isFinished()) { return; } long realFireTimeMs = System.currentTimeMillis(); long elapsedTimeMs = realFireTimeMs - absoluteStartTime; // the time should flow forward: we can have some better check here for NTP and maybe rise a warning assert elapsedTimeMs >= rateGenerator.lastComputedFireTimeMs(); long expectedNextFireTimeMs = rateGenerator.computeNextFireTime(elapsedTimeMs, this); // we need to make sure that the scheduling decisions are made based on the current time long rateGenerationDelayMs = System.currentTimeMillis() - realFireTimeMs; assert rateGenerationDelayMs >= 0; // given that both computeNextFireTime and onFireTimes can take some time, we need to adjust the fire time long scheduledFireDelayMs = Math.max(0, (expectedNextFireTimeMs - elapsedTimeMs) - rateGenerationDelayMs); if (trace) { log.trace("{}: {} after start, {} started ({} throttled), next user in {} ms, scheduling decisions took {} ms", def.name, elapsedTimeMs, rateGenerator.fireTimes(), throttledUsers, scheduledFireDelayMs, rateGenerationDelayMs); } if (scheduledFireDelayMs <= 0) { // we're so late that there's no point in bothering the executor with timers executorGroup.execute(() -> proceed(executorGroup)); } else { executorGroup.schedule(() -> proceed(executorGroup), scheduledFireDelayMs, TimeUnit.MILLISECONDS); } } @Override public void onFireTime() { if (!startNewSession()) { throttledUsers.incrementAndGet(); } } @Override public void notifyFinished(Session session) { if (session != null && !status.isFinished()) { long throttled = throttledUsers.get(); while (throttled != 0) { if (throttledUsers.compareAndSet(throttled, throttled - 1)) { // TODO: it would be nice to compensate response times // in these invocations for the fact that we're applying // SUT feedback, but that would be imprecise anyway. session.start(this); // this prevents the session to be pooled return; } else { throttled = throttledUsers.get(); } } } super.notifyFinished(session); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/LocalSimulationRunner.java
core/src/main/java/io/hyperfoil/core/impl/LocalSimulationRunner.java
package io.hyperfoil.core.impl; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.Executors; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.session.PhaseInstance; import io.hyperfoil.core.impl.statistics.StatisticsCollector; import io.vertx.core.Future; public class LocalSimulationRunner extends SimulationRunner { private final StatisticsCollector.StatisticsConsumer statsConsumer; private final SessionStatsConsumer sessionPoolStatsConsumer; private final ConnectionStatsConsumer connectionsStatsConsumer; private final Lock statusLock = new ReentrantLock(); private final Condition statusCondition = statusLock.newCondition(); private final StatisticsCollector statisticsCollector; private final ScheduledExecutorService statsExecutor = Executors.newSingleThreadScheduledExecutor(); private long startTime; public LocalSimulationRunner(Benchmark benchmark) { this(benchmark, null, null, null); } public LocalSimulationRunner(Benchmark benchmark, StatisticsCollector.StatisticsConsumer statsConsumer, SessionStatsConsumer sessionPoolStatsConsumer, ConnectionStatsConsumer connectionsStatsConsumer) { super(benchmark, "local-run", 0, error -> { }); statisticsCollector = new StatisticsCollector(benchmark); this.statsConsumer = statsConsumer; this.sessionPoolStatsConsumer = sessionPoolStatsConsumer; this.connectionsStatsConsumer = connectionsStatsConsumer; } public void run() { if (benchmark.phases().isEmpty()) { throw new BenchmarkDefinitionException("No phases/scenarios have been defined"); } CountDownLatch latch = new CountDownLatch(1); init(); openConnections(callable -> { try { callable.call(); } catch (Exception e) { return Future.failedFuture(e); } return Future.succeededFuture(); }, result -> latch.countDown()); try { latch.await(); statsExecutor.scheduleAtFixedRate(this::collectStats, 0, benchmark.statisticsCollectionPeriod(), TimeUnit.MILLISECONDS); // Exec is blocking and therefore must not run on the event-loop thread exec(); for (PhaseInstance phase : instances.values()) { if (phase.getError() != null) { throw new RuntimeException(phase.getError()); } } } catch (InterruptedException e) { throw new RuntimeException(e); } finally { statsExecutor.shutdown(); shutdown(); } } private void exec() { long now = System.currentTimeMillis(); this.startTime = now; do { now = System.currentTimeMillis(); for (PhaseInstance phase : instances.values()) { if (phase.status() == PhaseInstance.Status.RUNNING && phase.absoluteStartTime() + phase.definition().duration() <= now) { finishPhase(phase.definition().name()); } if (phase.status() == PhaseInstance.Status.FINISHED) { if (phase.definition().maxDuration() >= 0 && phase.absoluteStartTime() + phase.definition().maxDuration() <= now) { terminatePhase(phase.definition().name()); } else if (phase.definition().terminateAfterStrict().stream().map(instances::get) .allMatch(p -> p.status().isTerminated())) { tryTerminatePhase(phase.definition().name()); } } } PhaseInstance[] availablePhases = getAvailablePhases(); for (PhaseInstance phase : availablePhases) { startPhase(phase.definition().name()); } long nextPhaseStart = instances.values().stream() .filter(phase -> phase.status() == PhaseInstance.Status.NOT_STARTED && phase.definition().startTime() >= 0) .mapToLong(phase -> this.startTime + phase.definition().startTime()).min().orElse(Long.MAX_VALUE); long nextPhaseFinish = instances.values().stream() .filter(phase -> phase.status() == PhaseInstance.Status.RUNNING) .mapToLong(phase -> phase.absoluteStartTime() + phase.definition().duration()).min().orElse(Long.MAX_VALUE); long nextPhaseTerminate = instances.values().stream() .filter(phase -> (phase.status() == PhaseInstance.Status.RUNNING || phase.status() == PhaseInstance.Status.FINISHED) && phase.definition().maxDuration() >= 0) .mapToLong(phase -> phase.absoluteStartTime() + phase.definition().maxDuration()).min().orElse(Long.MAX_VALUE); long delay = Math.min(Math.min(nextPhaseStart, nextPhaseFinish), nextPhaseTerminate) - System.currentTimeMillis(); delay = Math.min(delay, 1000); if (delay > 0) { statusLock.lock(); try { statusCondition.await(delay, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { for (PhaseInstance phase : instances.values()) { terminatePhase(phase.definition().name()); } Thread.currentThread().interrupt(); } finally { statusLock.unlock(); } } } while (instances.values().stream().anyMatch(phase -> phase.status() != PhaseInstance.Status.STATS_COMPLETE)); } @Override protected CompletableFuture<Void> phaseChanged(Phase phase, PhaseInstance.Status status, boolean sessionLimitExceeded, Throwable error) { return super.phaseChanged(phase, status, sessionLimitExceeded, error).thenRun(() -> { if (status == PhaseInstance.Status.TERMINATED) { publishStats(phase); instances.get(phase.name).setStatsComplete(); } statusLock.lock(); try { statusCondition.signal(); } finally { statusLock.unlock(); } }); } private synchronized void publishStats(Phase phase) { if (statsConsumer != null) { visitStatistics(phase, statisticsCollector); statisticsCollector.visitStatistics(statsConsumer, null); } if (sessionPoolStatsConsumer != null) { visitSessionPoolStats(phase, sessionPoolStatsConsumer); } if (connectionsStatsConsumer != null) { visitConnectionStats(connectionsStatsConsumer); } } private synchronized void collectStats() { visitStatistics(statisticsCollector); } private PhaseInstance[] getAvailablePhases() { return instances.values().stream().filter(phase -> phase.status() == PhaseInstance.Status.NOT_STARTED && startTime + phase.definition().startTime() <= System.currentTimeMillis() && phase.definition().startAfter().stream().allMatch(dep -> instances.get(dep).status().isFinished()) && phase.definition().startAfterStrict().stream().allMatch(dep -> instances.get(dep).status().isTerminated()) && (phase.definition().startWithDelay() == null || instances.get(phase.definition().startWithDelay().phase).status().isStarted() && instances.get(phase.definition().startWithDelay().phase).absoluteStartTime() + phase.definition().startWithDelay().delay <= System.currentTimeMillis())) .toArray(PhaseInstance[]::new); } /** * More for testing purposes, allow internal phases inspection * * @return the phase instances map */ public Map<String, PhaseInstance> instances() { return instances; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/AffinityAwareSessionPool.java
core/src/main/java/io/hyperfoil/core/impl/AffinityAwareSessionPool.java
package io.hyperfoil.core.impl; import java.util.IdentityHashMap; import java.util.Objects; import java.util.Queue; import java.util.concurrent.ThreadLocalRandom; import java.util.concurrent.atomic.AtomicIntegerArray; import java.util.function.Supplier; import org.jctools.queues.MpmcArrayQueue; import org.jctools.queues.atomic.MpmcAtomicArrayQueue; import io.hyperfoil.api.collection.ElasticPool; import io.hyperfoil.api.session.Session; import io.netty.util.concurrent.EventExecutor; import io.netty.util.concurrent.FastThreadLocal; import io.netty.util.internal.PlatformDependent; import io.netty.util.internal.ThreadExecutorMap; /** * This class represents a pool of sessions that are aware of thread affinity. * It implements the {@link ElasticPool} interface and provides methods to acquire and release sessions.<br> * The pool maintains a separate queue of sessions for each event executor (thread), * and tries to acquire and release sessions from the queue of the current executor. * If the local queue is empty, it tries to steal sessions from other queues. */ public class AffinityAwareSessionPool implements ElasticPool<Session> { private final FastThreadLocal<Integer> localAgentThreadId; private final IdentityHashMap<EventExecutor, Integer> agentThreadIdPerExecutor; private final Queue<Session>[] localQueues; private final Supplier<Session> sessionSupplier; /** * We're using a single array to store multiple counters, mostly to avoid false sharing with other fields * in this same class (which are mostly read-only).<br> * We still pad used/min/max from each others to avoid max and min to interfere with each other. * There's no point to use a LongAdder here, because reading the counters would hit worse than sharing a single one * which can leverage fast x86 fetch-and-add instructions. */ private static final int PADDING_INTS = 128 / Integer.BYTES; // 32 private static final int USED_OFFSET = PADDING_INTS; // 32 private static final int MIN_USED_OFFSET = USED_OFFSET + PADDING_INTS; // 32 + 32 = 64 private static final int MAX_USED_OFFSET = MIN_USED_OFFSET + PADDING_INTS; // 64 + 32 = 96 private static final int COUNTERS_INTS = MAX_USED_OFFSET + PADDING_INTS; // 96 + 32 = 128 private final AtomicIntegerArray counters; public AffinityAwareSessionPool(EventExecutor[] eventExecutors, Supplier<Session> sessionSupplier) { this.sessionSupplier = sessionSupplier; this.agentThreadIdPerExecutor = new IdentityHashMap<>(eventExecutors.length); this.localQueues = new Queue[eventExecutors.length]; for (int agentThreadId = 0; agentThreadId < eventExecutors.length; agentThreadId++) { agentThreadIdPerExecutor.put(eventExecutors[agentThreadId], agentThreadId); } this.localAgentThreadId = new FastThreadLocal<>() { @Override protected Integer initialValue() { var eventExecutor = ThreadExecutorMap.currentExecutor(); return eventExecutor == null ? null : agentThreadIdPerExecutor.get(eventExecutor); } }; this.counters = new AtomicIntegerArray(COUNTERS_INTS); } private int nextWorkStealIndex() { return ThreadLocalRandom.current().nextInt(0, localQueues.length); } private int nextWorkStealIndex(int excludeIndex) { var localQueuesCount = localQueues.length; var workStealIndex = localQueuesCount == 2 ? excludeIndex : ThreadLocalRandom.current().nextInt(0, localQueuesCount); if (workStealIndex == excludeIndex) { workStealIndex++; if (workStealIndex == localQueuesCount) { workStealIndex = 0; } } return workStealIndex; } @Override public Session acquire() { var boxedAgentThreadId = localAgentThreadId.get(); if (boxedAgentThreadId == null) { return acquireFromLocalQueues(); } // explicitly unbox to save unboxing it again, in case work-stealing happens var agentThreadId = boxedAgentThreadId.intValue(); var localQueues = this.localQueues; var session = localQueues[agentThreadId].poll(); if (session != null) { incrementUsed(); return session; } if (localQueues.length == 1) { return null; } return acquireFromOtherLocalQueues(localQueues, agentThreadId); } private Session acquireFromLocalQueues() { int currentIndex = nextWorkStealIndex(); var localQueues = this.localQueues; int localQueuesCount = localQueues.length; for (Queue<Session> localQueue : localQueues) { Session session = localQueue.poll(); if (session != null) { incrementUsed(); return session; } currentIndex++; if (currentIndex == localQueuesCount) { currentIndex = 0; } } return null; } private Session acquireFromOtherLocalQueues(Queue<Session>[] localQueues, int agentThreadIdToSkip) { int currentIndex = nextWorkStealIndex(agentThreadIdToSkip); var localQueuesCount = localQueues.length; // this loop start from the workStealIndex, but while iterating can still end up // at the index we want to ignore, so we need to skip it for (int i = 0; i < localQueuesCount; i++) { if (currentIndex != agentThreadIdToSkip) { var localQ = localQueues[currentIndex]; if (localQ != null) { var session = localQ.poll(); if (session != null) { incrementUsed(); return session; } } } currentIndex++; if (currentIndex == localQueuesCount) { currentIndex = 0; } } return null; } private void incrementUsed() { var counters = this.counters; int used = counters.incrementAndGet(USED_OFFSET); int maxUsed = counters.get(MAX_USED_OFFSET); if (used > maxUsed) { counters.lazySet(MAX_USED_OFFSET, used); } } private void decrementUsed() { var counters = this.counters; int used = counters.decrementAndGet(USED_OFFSET); int minUsed = counters.get(MIN_USED_OFFSET); if (minUsed > 0 && used < minUsed) { counters.lazySet(MIN_USED_OFFSET, used); } } @Override public void release(Session session) { Objects.requireNonNull(session); var localQueue = localQueues[session.agentThreadId()]; decrementUsed(); localQueue.add(session); } @Override public void reserve(int capacity) { int totalCapacity = getLocalQueuesCapacity(); if (totalCapacity >= capacity) { return; } moveNewSessionsToLocalQueues(capacity, totalCapacity); } private int getLocalQueuesCapacity() { int totalCapacity = 0; for (Queue<Session> localQueue : localQueues) { if (localQueue != null) { totalCapacity += localQueue.size(); } } return totalCapacity; } private void moveNewSessionsToLocalQueues(int requiredCapacity, int currentCapacity) { final int newCapacity = requiredCapacity - currentCapacity; // assume fair distribution of new sessions var perEventExecutorNewCapacity = (int) Math.ceil((double) newCapacity / localQueues.length); var sessionSupplier = this.sessionSupplier; var localQueues = this.localQueues; var agentThreadIdPerExecutor = this.agentThreadIdPerExecutor; // It keeps track of the local queues capacity not yet reserved boolean[] localQueueReservedCapacity = new boolean[localQueues.length]; for (int i = 0; i < newCapacity; i++) { var newSession = sessionSupplier.get(); var eventExecutor = newSession.executor(); var boxedAgentThreadId = agentThreadIdPerExecutor.get(eventExecutor); if (boxedAgentThreadId == null) { throw new IllegalStateException("No agentThreadId for executor " + eventExecutor); } var agentThreadId = boxedAgentThreadId.intValue(); var localQueue = localQueues[agentThreadId]; if (!localQueueReservedCapacity[agentThreadId]) { localQueueReservedCapacity[agentThreadId] = true; if (localQueue == null) { localQueue = createLocalQueue(perEventExecutorNewCapacity); localQueues[agentThreadId] = localQueue; } else { var newLocalQueue = createLocalQueue(localQueue.size() + perEventExecutorNewCapacity); newLocalQueue.addAll(localQueue); localQueue.clear(); localQueue = newLocalQueue; localQueues[agentThreadId] = newLocalQueue; } } if (!localQueue.offer(newSession)) { throw new IllegalStateException("Failed to add new session to local queue: sessions are not fairly distributed"); } } for (int i = 0; i < localQueueReservedCapacity.length; i++) { if (!localQueueReservedCapacity[i]) { var localQ = localQueues[i]; if (localQ == null) { localQ = createLocalQueue(0); this.localQueues[i] = localQ; } } } } private Queue<Session> createLocalQueue(int capacity) { if (PlatformDependent.hasUnsafe()) { return new MpmcArrayQueue<>(Math.max(2, capacity)); } return new MpmcAtomicArrayQueue<>(Math.max(2, capacity)); } @Override public int minUsed() { return counters.get(MIN_USED_OFFSET); } @Override public int maxUsed() { return counters.get(MAX_USED_OFFSET); } @Override public void resetStats() { var counters = this.counters; int used = counters.get(USED_OFFSET); counters.lazySet(MAX_USED_OFFSET, used); counters.lazySet(MIN_USED_OFFSET, used); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/LockBasedElasticPool.java
core/src/main/java/io/hyperfoil/core/impl/LockBasedElasticPool.java
package io.hyperfoil.core.impl; import java.util.Objects; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.LongAdder; import java.util.function.Supplier; import io.hyperfoil.api.collection.ElasticPool; public class LockBasedElasticPool<T> implements ElasticPool<T> { protected final LongAdder used = new LongAdder(); private final Supplier<T> initSupplier; private final Supplier<T> depletionSupplier; protected volatile int minUsed; protected volatile int maxUsed; private ArrayBlockingQueue<T> primaryQueue; private final BlockingQueue<T> secondaryQueue = new LinkedBlockingQueue<>(); public LockBasedElasticPool(Supplier<T> initSupplier, Supplier<T> depletionSupplier) { this.initSupplier = initSupplier; this.depletionSupplier = depletionSupplier; } @Override public T acquire() { T object = primaryQueue.poll(); if (object != null) { incrementUsed(); return object; } object = secondaryQueue.poll(); if (object != null) { incrementUsed(); return object; } object = depletionSupplier.get(); if (object != null) { incrementUsed(); } return object; } @Override public void release(T object) { Objects.requireNonNull(primaryQueue); decrementUsed(); if (primaryQueue.offer(object)) { return; } secondaryQueue.add(object); } @Override public void reserve(int capacity) { if (primaryQueue == null || primaryQueue.size() < capacity) { primaryQueue = new ArrayBlockingQueue<>(capacity); } while (primaryQueue.size() < capacity) { primaryQueue.add(initSupplier.get()); } } public void incrementUsed() { used.increment(); long currentlyUsed = used.longValue(); if (currentlyUsed > maxUsed) { maxUsed = (int) currentlyUsed; } } public void decrementUsed() { decrementUsed(1); } public void decrementUsed(int num) { used.add(-num); long currentlyUsed = used.longValue(); if (currentlyUsed < minUsed) { minUsed = (int) currentlyUsed; } assert currentlyUsed >= 0; } @Override public int minUsed() { return minUsed; } @Override public int maxUsed() { return maxUsed; } @Override public void resetStats() { int current = used.intValue(); minUsed = current; maxUsed = current; } public int current() { return used.intValue(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/EventLoopFactory.java
core/src/main/java/io/hyperfoil/core/impl/EventLoopFactory.java
package io.hyperfoil.core.impl; import io.hyperfoil.internal.Properties; import io.netty.channel.EventLoopGroup; import io.netty.channel.epoll.Epoll; import io.netty.channel.epoll.EpollEventLoopGroup; import io.netty.channel.epoll.EpollSocketChannel; import io.netty.channel.kqueue.KQueue; import io.netty.channel.kqueue.KQueueEventLoopGroup; import io.netty.channel.kqueue.KQueueSocketChannel; import io.netty.channel.nio.NioEventLoopGroup; import io.netty.channel.socket.SocketChannel; import io.netty.channel.socket.nio.NioSocketChannel; public abstract class EventLoopFactory { public static final EventLoopFactory INSTANCE; static { String transport = Properties.get(Properties.NETTY_TRANSPORT, null); if (transport != null) { switch (transport.toLowerCase()) { case "nio": INSTANCE = new NioEventLoopFactory(); break; case "epoll": INSTANCE = new EpollEventLoopFactory(); break; case "kqueue": INSTANCE = new KqueueEventLoopFactory(); break; // TODO: io_uring requires kernel >= 5.9 default: throw new IllegalStateException("Unknown transport '" + transport + "', use either 'nio' or 'epoll'."); } } else { if (Epoll.isAvailable()) { INSTANCE = new EpollEventLoopFactory(); } else if (KQueue.isAvailable()) { INSTANCE = new KqueueEventLoopFactory(); } else { INSTANCE = new NioEventLoopFactory(); } } } public abstract EventLoopGroup create(int threads); public abstract Class<? extends SocketChannel> socketChannel(); private static class NioEventLoopFactory extends EventLoopFactory { @Override public EventLoopGroup create(int threads) { return new NioEventLoopGroup(threads); } @Override public Class<? extends SocketChannel> socketChannel() { return NioSocketChannel.class; } } private static class EpollEventLoopFactory extends EventLoopFactory { @Override public EventLoopGroup create(int threads) { return new EpollEventLoopGroup(threads); } @Override public Class<? extends SocketChannel> socketChannel() { return EpollSocketChannel.class; } } private static class KqueueEventLoopFactory extends EventLoopFactory { @Override public EventLoopGroup create(int threads) { return new KQueueEventLoopGroup(threads); } @Override public Class<? extends SocketChannel> socketChannel() { return KQueueSocketChannel.class; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/SessionStatsConsumer.java
core/src/main/java/io/hyperfoil/core/impl/SessionStatsConsumer.java
package io.hyperfoil.core.impl; public interface SessionStatsConsumer { void accept(String phase, int minSessions, int maxSessions); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/statistics/StatisticsCollector.java
core/src/main/java/io/hyperfoil/core/impl/statistics/StatisticsCollector.java
package io.hyperfoil.core.impl.statistics; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.function.Consumer; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.statistics.SessionStatistics; import io.hyperfoil.api.statistics.Statistics; import io.hyperfoil.api.statistics.StatisticsSnapshot; import io.hyperfoil.core.util.CountDown; import io.netty.util.collection.IntObjectHashMap; import io.netty.util.collection.IntObjectMap; public class StatisticsCollector implements Consumer<SessionStatistics> { private static final Logger log = LogManager.getLogger(StatisticsCollector.class); private static final boolean trace = log.isTraceEnabled(); protected final Phase[] phases; protected IntObjectMap<Map<String, IntObjectMap<StatisticsSnapshot>>> aggregated = new IntObjectHashMap<>(); public StatisticsCollector(Benchmark benchmark) { this.phases = benchmark.phasesById(); } @Override public void accept(SessionStatistics statistics) { for (int i = 0; i < statistics.size(); ++i) { int phaseAndStepId = (statistics.phase(i).id() << 16) + statistics.step(i); Map<String, IntObjectMap<StatisticsSnapshot>> metricMap = aggregated.get(phaseAndStepId); if (metricMap == null) { metricMap = new HashMap<>(); aggregated.put(phaseAndStepId, metricMap); } for (Map.Entry<String, Statistics> entry : statistics.stats(i).entrySet()) { String metric = entry.getKey(); IntObjectMap<StatisticsSnapshot> snapshots = metricMap.computeIfAbsent(metric, k -> new IntObjectHashMap<>()); entry.getValue().visitSnapshots(snapshot -> { assert snapshot.sequenceId >= 0; StatisticsSnapshot existing = snapshots.get(snapshot.sequenceId); if (existing == null) { existing = new StatisticsSnapshot(); existing.sequenceId = snapshot.sequenceId; snapshots.put(snapshot.sequenceId, existing); } existing.add(snapshot); }); } } } public void visitStatistics(StatisticsConsumer consumer, CountDown countDown) { for (Iterator<Map.Entry<Integer, Map<String, IntObjectMap<StatisticsSnapshot>>>> it1 = aggregated.entrySet() .iterator(); it1.hasNext();) { Map.Entry<Integer, Map<String, IntObjectMap<StatisticsSnapshot>>> entry = it1.next(); int phaseAndStepId = entry.getKey(); Map<String, IntObjectMap<StatisticsSnapshot>> metricMap = entry.getValue(); for (Iterator<Map.Entry<String, IntObjectMap<StatisticsSnapshot>>> it2 = metricMap.entrySet().iterator(); it2 .hasNext();) { Map.Entry<String, IntObjectMap<StatisticsSnapshot>> se = it2.next(); String metric = se.getKey(); IntObjectMap<StatisticsSnapshot> snapshots = se.getValue(); for (Iterator<IntObjectMap.PrimitiveEntry<StatisticsSnapshot>> it3 = snapshots.entries().iterator(); it3 .hasNext();) { IntObjectMap.PrimitiveEntry<StatisticsSnapshot> pe = it3.next(); if (pe.value().isEmpty()) { it3.remove(); } else { consumer.accept(phases[phaseAndStepId >> 16], phaseAndStepId & 0xFFFF, metric, pe.value(), countDown); pe.value().reset(); } } if (snapshots.isEmpty()) { it2.remove(); } } if (metricMap.isEmpty()) { it1.remove(); } } } public interface StatisticsConsumer { void accept(Phase phase, int stepId, String metric, StatisticsSnapshot snapshot, CountDown countDown); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/rate/PoissonRampRateGenerator.java
core/src/main/java/io/hyperfoil/core/impl/rate/PoissonRampRateGenerator.java
package io.hyperfoil.core.impl.rate; import java.util.Random; /** * This generator is computing the time for the next event to be scheduled in order that the total events * follow a non-homogeneous Poisson process with a linearly increasing rate.<br> * Similarly to {@link PoissonConstantRateGenerator}, the generator is computing the time for the next event * to be scheduled based on the previous one, but the inverse transform sampling method to produce samples * depends on rate(t) instead of a constant rate i.e. fireTimesPerSec.<br> * Such function is defined as:<br> * {@code T = -log(rand) / rate(t)}<br> * The rate function <code>rate(t)</code> is a linear function of time, defined as:<br> * <code>rate(t) = initialFireTimesPerSec + (targetFireTimesPerSec - initialFireTimesPerSec) * (elapsedTimeMs / durationMs)</code><br> * To compute the time interval {@code T} until the next event, we need to solve the integral equation that accounts for the * non-homogeneous Poisson process with a time-varying rate function.<br> * The process can be broken down as follows: * <ol> * <li>Since {@code rate(t)} is not constant but changes linearly over time, we need to consider the integration of the rate * function over the interval [0, T]. * <br> * Intuitively, we can look back at the previous formula {@code T = -log(rand) / rate(t)} as {@code rate(t) * T = -log(rand)} * where {@code rate(t) * T} are the number of * fire times in the period T.<br> * This information can be obtained as the area of the rate(t) function from 0 to T, which is the mentioned integral.<br> * <br> * The integral equation is: * {@code ∫[0 to T] (initialFireTimesPerSec + (targetFireTimesPerSec - initialFireTimesPerSec) * (t / durationMs)) dt = -log(rand)} * </li> * <li>The left-hand side of the equation is: * <br> * {@code (initialFireTimesPerSec * T) + ((targetFireTimesPerSec - initialFireTimesPerSec) * T^2) / (2 * durationMs)} * </li> * <li>Set this equal to {@code -log(rand)} and solve for {@code T}: * <br> * {@code initialFireTimesPerSec * T + ((targetFireTimesPerSec - initialFireTimesPerSec) * T^2) / (2 * durationMs) = -log(rand)} * </li> * <li>This is a quadratic equation of the form: * <br> * {@code aT^2 + bT + c = 0} * <br> * where: * <ul> * <li>{@code a = (targetFireTimesPerSec - initialFireTimesPerSec) / (2 * durationMs)}</li> * <li>{@code b = initialFireTimesPerSec}</li> * <li>{@code c = -log(rand)}</li> * </ul> * </li> * <li>Use the quadratic formula to solve for {@code T}: * <br> * {@code T = (-b ± sqrt(b^2 - 4ac)) / (2a)} * </li> * <li>Since time intervals cannot be negative, choose the positive root: * <br> * {@code T = (-initialFireTimesPerSec + sqrt(initialFireTimesPerSec^2 - 4 * (targetFireTimesPerSec - initialFireTimesPerSec) * (-log(rand) / (2 * durationMs)))) / ((targetFireTimesPerSec - initialFireTimesPerSec) / durationMs)} * </li> * <li>Simplify the expression to get the value of {@code T}. * <br> * The result is the time interval {@code T} for the next event to be scheduled. Add this interval to the current elapsed time. * </li> * </ol> */ final class PoissonRampRateGenerator extends SequentialRateGenerator { private final double initialFireTimesPerSec; private final Random random; private final long duration; private final double aCoef; PoissonRampRateGenerator(final Random random, final double initialFireTimesPerSec, final double targetFireTimesPerSec, final long durationMs) { this.initialFireTimesPerSec = initialFireTimesPerSec; this.duration = durationMs; this.aCoef = (targetFireTimesPerSec - initialFireTimesPerSec); this.random = random; fireTimeMs = nextFireTimeMs(0); } @Override protected double nextFireTimeMs(final double elapsedTimeMs) { // we're solving quadratic equation coming from t = (duration * -log(rand))/(((t + now) * (target - initial)) + initial * duration) final double bCoef = elapsedTimeMs * aCoef + initialFireTimesPerSec * duration; final double cCoef = duration * 1000 * Math.log(random.nextDouble()); return elapsedTimeMs + (-bCoef + Math.sqrt(bCoef * bCoef - 4 * aCoef * cCoef)) / (2 * aCoef); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/rate/FunctionalRateGenerator.java
core/src/main/java/io/hyperfoil/core/impl/rate/FunctionalRateGenerator.java
package io.hyperfoil.core.impl.rate; public abstract class FunctionalRateGenerator extends BaseRateGenerator { protected abstract long computeFireTimes(long elapsedTimeMs); protected abstract double computeFireTimeMs(long targetFireTimes); @Override public long computeNextFireTime(final long elapsedTimeMs, FireTimeListener listener) { if (elapsedTimeMs < fireTimeMs) { return (long) Math.ceil(fireTimeMs); } final long fireTimes = computeFireTimes(elapsedTimeMs) + 1; final double nextFireTimeMs = computeFireTimeMs(fireTimes); fireTimeMs = nextFireTimeMs; long missingFireTimes = fireTimes - this.fireTimes; this.fireTimes = fireTimes; listener.onFireTimes(missingFireTimes); return (long) Math.ceil(nextFireTimeMs); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/rate/BaseRateGenerator.java
core/src/main/java/io/hyperfoil/core/impl/rate/BaseRateGenerator.java
package io.hyperfoil.core.impl.rate; public abstract class BaseRateGenerator implements RateGenerator { protected double fireTimeMs; protected long fireTimes; public BaseRateGenerator() { fireTimeMs = 0; } @Override public long fireTimes() { return fireTimes; } @Override public long lastComputedFireTimeMs() { return (long) Math.ceil(fireTimeMs); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/rate/SequentialRateGenerator.java
core/src/main/java/io/hyperfoil/core/impl/rate/SequentialRateGenerator.java
package io.hyperfoil.core.impl.rate; abstract class SequentialRateGenerator extends BaseRateGenerator { protected abstract double nextFireTimeMs(double elapsedTimeMs); @Override public final long computeNextFireTime(final long elapsedTimeMs, FireTimeListener listener) { long fireTimesToMillis = 0; double nextFireTimeMs = fireTimeMs; while (elapsedTimeMs >= nextFireTimeMs) { listener.onFireTime(); fireTimesToMillis++; nextFireTimeMs = nextFireTimeMs(nextFireTimeMs); } fireTimeMs = nextFireTimeMs; this.fireTimes += fireTimesToMillis; return (long) Math.ceil(nextFireTimeMs); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/rate/RampRateGenerator.java
core/src/main/java/io/hyperfoil/core/impl/rate/RampRateGenerator.java
package io.hyperfoil.core.impl.rate; /** * This is a generator that generates events (fire times) at a ramping rate. * The rate of events starts at an initial rate and increases linearly to a target rate over a specified duration. * <p> * The rate function is a linear function of time, defined as: * * <pre>{@code * rate(t) = initialFireTimesPerSec + (targetFireTimesPerSec - initialFireTimesPerSec) * (elapsedTimeMs / durationMs) * }</pre> * * To find the required number of events at time t, we need to integrate the rate function from 0 to t: * * <pre>{@code * requiredFireTimes(t) = ∫[0 to t] (initialFireTimesPerSec + (targetFireTimesPerSec - initialFireTimesPerSec) * (t / durationMs)) dt * }</pre> * * Which simplifies to: * * <pre>{@code * requiredFireTimes(t) = (initialFireTimesPerSec * t) * + ((targetFireTimesPerSec - initialFireTimesPerSec) * t ^ 2) / (2 * durationMs) * }</pre> * * Given the elapsed time {@code t} we can use the above formula to compute the required number of events.<br> * To obtain the next fire time, we need to solve the integral equation for the required number of events at time t.<br> * Assuming the required number of events at time t is known (using the previous formula and adding another one), * we can resolve the previous equation for t rearranging it into a quadratic equation of the form aT^2 + bT + c = 0.<br> * <p> * Let: * <ul> * <li>{@code a = (targetFireTimesPerSec - initialFireTimesPerSec) / (2 * durationMs)}</li> * <li>{@code b = initialFireTimesPerSec}</li> * <li>{@code c = -requiredFireTimes(t)}</li> * </ul> * Solving this quadratic equation for {@code t} provides the time at which the next event should be scheduled. */ final class RampRateGenerator extends FunctionalRateGenerator { private final double bCoef; private final double progress; RampRateGenerator(final double initialFireTimesPerSec, final double targetFireTimesPerSec, final long durationMs) { bCoef = initialFireTimesPerSec / 1000; progress = (targetFireTimesPerSec - initialFireTimesPerSec) / (durationMs * 1000); } @Override protected long computeFireTimes(final long elapsedTimeMs) { return (long) ((progress * elapsedTimeMs / 2 + bCoef) * elapsedTimeMs); } @Override protected double computeFireTimeMs(final long targetFireTimes) { // root of quadratic equation return Math.ceil((-bCoef + Math.sqrt(bCoef * bCoef + 2 * progress * targetFireTimes)) / progress); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/rate/FireTimeListener.java
core/src/main/java/io/hyperfoil/core/impl/rate/FireTimeListener.java
package io.hyperfoil.core.impl.rate; @FunctionalInterface public interface FireTimeListener { void onFireTime(); default void onFireTimes(long count) { for (long i = 0; i < count; i++) { onFireTime(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/rate/RateGenerator.java
core/src/main/java/io/hyperfoil/core/impl/rate/RateGenerator.java
package io.hyperfoil.core.impl.rate; import java.util.Random; public interface RateGenerator { long computeNextFireTime(long elapsedMillis, FireTimeListener listener); long lastComputedFireTimeMs(); long fireTimes(); static RateGenerator constantRate(double fireTimesPerSec) { return new ConstantRateGenerator(fireTimesPerSec); } static RateGenerator rampRate(double initialFireTimesPerSec, double targetFireTimesPerSec, long durationMs) { if (Math.abs(targetFireTimesPerSec - initialFireTimesPerSec) < 0.000001) { return constantRate(initialFireTimesPerSec); } return new RampRateGenerator(initialFireTimesPerSec, targetFireTimesPerSec, durationMs); } static RateGenerator poissonConstantRate(Random random, double usersPerSec) { return new PoissonConstantRateGenerator(random, usersPerSec); } static RateGenerator poissonConstantRate(double usersPerSec) { return poissonConstantRate(new Random(), usersPerSec); } static RateGenerator poissonRampRate(Random random, double initialFireTimesPerSec, double targetFireTimesPerSec, long durationMs) { if (Math.abs(targetFireTimesPerSec - initialFireTimesPerSec) < 0.000001) { return poissonConstantRate(random, initialFireTimesPerSec); } return new PoissonRampRateGenerator(random, initialFireTimesPerSec, targetFireTimesPerSec, durationMs); } static RateGenerator poissonRampRate(double initialFireTimesPerSec, double targetFireTimesPerSec, long durationMs) { return poissonRampRate(new Random(), initialFireTimesPerSec, targetFireTimesPerSec, durationMs); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/rate/ConstantRateGenerator.java
core/src/main/java/io/hyperfoil/core/impl/rate/ConstantRateGenerator.java
package io.hyperfoil.core.impl.rate; final class ConstantRateGenerator extends FunctionalRateGenerator { private final double fireTimesPerSec; ConstantRateGenerator(final double fireTimesPerSec) { this.fireTimesPerSec = fireTimesPerSec; } @Override protected long computeFireTimes(final long elapsedTimeMs) { return (long) (elapsedTimeMs * fireTimesPerSec / 1000); } @Override protected double computeFireTimeMs(final long targetFireTimes) { return 1000 * targetFireTimes / fireTimesPerSec; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/impl/rate/PoissonConstantRateGenerator.java
core/src/main/java/io/hyperfoil/core/impl/rate/PoissonConstantRateGenerator.java
package io.hyperfoil.core.impl.rate; import java.util.Random; /** * This generator is computing the time for the next event to be scheduled in order that the total events * follow a homogeneous Poisson process.<br> * <br> * Given this formula to compute the next fire time based on the previous one<br> * <br> * <code>fireTime(t) = fireTime(t -1) + T</code><br> * <br> * {@code T} is a random variable that follows an exponential distribution with rate {@code fireTimesPerSec}.<br> * <br> * The formula to compute the next fire time is:<br> * <br> * <code>fireTime(t) = fireTime(t -1) + -log(rand) / fireTimesPerSec</code><br> * <br> * where the T part (exponential distribution) is computed as {@code -log(rand) / fireTimesPerSec} * and uses the <a href="https://en.wikipedia.org/wiki/Inverse_transform_sampling">inverse transform sampling method<a/> * to generate such intervals following an exponential distribution.<br> * <br> * Specifically, the exponential distribution is defined as:<br> * <br> * <code>f(x) = fireTimesPerSec * exp(-fireTimesPerSec * x)</code><br> * <br> * where {@code x} is the random variable and {@code fireTimesPerSec} is the rate of the distribution.<br> * <br> * In order to generate samples which follow it we need to compute the inverse function of the cumulative distribution function * (CDF).<br> * <br> * The CDF of the exponential distribution is obtained by integrating the probability density function (PDF) from 0 to {@code x} * and is defined as:<br> * <br> * <code>F(x) = 1 - exp(-fireTimesPerSec * x)</code><br> * <br> * We can transform this function by performing the logarithm of both sides:<br> * <br> * <code>log(1 - F(x)) = -fireTimesPerSec * x</code><br> * <br> * Resolving the previous equation for {@code x} we get:<br> * <br> * <code>x = -log(1 - F(x)) / fireTimesPerSec</code><br> * <br> * But given that {@code F(x)} is a random variable that follows a uniform distribution between 0 and 1, {@code 1 - F(x)} * is also a random variable that follows a uniform distribution between 0 and 1.<br> * <br> * Therefore, the formula to generate samples that follow an exponential distribution is:<br> * <br> * <code>x = -log(rand) / fireTimesPerSec</code><br> * <br> * which is the inverse function of the CDF of the exponential distribution and {@code x} is a random variable * that follows a uniform distribution between 0 and 1.<br> * <br> */ final class PoissonConstantRateGenerator extends SequentialRateGenerator { private final Random random; private final double fireTimesPerSec; PoissonConstantRateGenerator(final Random random, final double fireTimesPerSec) { this.random = random; this.fireTimesPerSec = fireTimesPerSec; this.fireTimeMs = nextFireTimeMs(0); } @Override protected double nextFireTimeMs(final double elapsedTimeMs) { // the Math.max(1e-20, random.nextDouble()) is to prevent the logarithm to be negative infinity, because // the random number can approach to 0 and the logarithm of 0 is negative infinity return elapsedTimeMs + 1000 * -Math.log(Math.max(1e-20, random.nextDouble())) / fireTimesPerSec; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/generators/RandomItemStep.java
core/src/main/java/io/hyperfoil/core/generators/RandomItemStep.java
package io.hyperfoil.core.generators; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.lang.reflect.Array; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Objects; import java.util.concurrent.ThreadLocalRandom; import java.util.stream.Stream; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Locator; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.config.StepBuilder; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.BaseStepBuilder; import io.hyperfoil.core.session.ObjectVar; import io.hyperfoil.core.session.SessionFactory; public class RandomItemStep implements Step { private final ReadAccess fromVar; private final WeightedGenerator generator; private final ObjectAccess toVar; public RandomItemStep(ReadAccess fromVar, WeightedGenerator generator, ObjectAccess toVar) { this.fromVar = fromVar; this.generator = generator; this.toVar = toVar; } @Override public boolean invoke(Session session) { ThreadLocalRandom random = ThreadLocalRandom.current(); Object item; if (generator != null) { assert fromVar == null; item = generator.randomItem(); } else { Object data = fromVar.getObject(session); if (data instanceof ObjectVar[]) { // Assume that first unset variable denotes end of set variables ObjectVar[] array = (ObjectVar[]) data; int length = array.length; for (int i = 0; i < array.length; ++i) { if (!array[i].isSet()) { length = i; break; } } if (length > 0) { item = array[random.nextInt(length)].objectValue(session); } else { throw new IllegalStateException("Collection " + fromVar + " is empty, can not select a random item"); } } else if (data != null && data.getClass().isArray()) { int length = Array.getLength(data); item = Array.get(data, random.nextInt(length)); } else if (data instanceof List) { List<?> dataList = (List<?>) data; item = dataList.get(random.nextInt(dataList.size())); } else if (data instanceof Collection) { Collection<?> dataCollection = (Collection<?>) data; Iterator<?> iterator = dataCollection.iterator(); for (int i = random.nextInt(dataCollection.size()) - 1; i > 0; --i) { iterator.next(); } item = iterator.next(); } else { throw new IllegalStateException("Cannot fetch random item from collection stored under " + fromVar + ": " + data); } } toVar.setObject(session, item); return true; } /** * Stores random item from a list or array into session variable. */ @MetaInfServices(StepBuilder.class) @Name("randomItem") public static class Builder extends BaseStepBuilder<Builder> implements InitFromParam<Builder> { private String fromVar; private WeightedGenerator.Builder<Builder> weighted; private String file; private String toVar; /** * @param toFrom Use `toVar &lt;- fromVar` where fromVar is an array/collection. * @return Self. */ @Override public Builder init(String toFrom) { if (toFrom == null) { return this; } String[] parts = toFrom.split("<-"); if (parts.length != 2) { throw new BenchmarkDefinitionException("Expecting format toVar <- fromVar"); } toVar = parts[0].trim(); fromVar = parts[1].trim(); return this; } @Override public List<Step> build() { if (toVar == null || toVar.isEmpty()) { throw new BenchmarkDefinitionException("toVar is empty"); } long usedProperties = Stream.of(file, weighted, fromVar).filter(Objects::nonNull).count(); if (usedProperties > 1) { throw new BenchmarkDefinitionException("randomItem cannot combine `fromVar` and `list` or `file`"); } else if (usedProperties == 0) { throw new BenchmarkDefinitionException("randomItem must define one of: `fromVar`, `list` or `file`"); } WeightedGenerator generator; if (weighted != null) { generator = weighted.build(); } else if (file != null) { List<String> list = new ArrayList<>(); try (InputStream inputStream = Locator.current().benchmark().data().readFile(file)) { try (BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, StandardCharsets.UTF_8))) { String line; while ((line = reader.readLine()) != null) { if (!line.isEmpty()) { list.add(line); } } } } catch (IOException e) { throw new BenchmarkDefinitionException("Cannot load file `" + file + "` for randomItem.", e); } generator = new WeightedGenerator(null, list.toArray(new String[0])); } else { if (fromVar.isEmpty()) { throw new BenchmarkDefinitionException("fromVar is empty"); } generator = null; } return Collections.singletonList(new RandomItemStep(SessionFactory.readAccess(fromVar), generator, SessionFactory.objectAccess(toVar))); } /** * Variable containing an array or list. * * @param fromVar Variable name. * @return Self. */ public Builder fromVar(String fromVar) { this.fromVar = fromVar; return this; } /** * Potentially weighted list of items to choose from. * * @return Builder. */ public WeightedGenerator.Builder<Builder> list() { if (weighted == null) { weighted = new WeightedGenerator.Builder<>(this); } return weighted; } /** * Variable where the chosen item should be stored. * * @param var Variable name. * @return Self. */ public Builder toVar(String var) { this.toVar = var; return this; } /** * This file will be loaded into memory and the step will choose on line as the item. * * @param file Path to the file. * @return Self. */ public Builder file(String file) { this.file = file; return this; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/generators/StringGeneratorBuilder.java
core/src/main/java/io/hyperfoil/core/generators/StringGeneratorBuilder.java
package io.hyperfoil.core.generators; import io.hyperfoil.api.session.Session; import io.hyperfoil.function.SerializableFunction; public interface StringGeneratorBuilder { SerializableFunction<Session, String> build(); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/generators/TemplateStep.java
core/src/main/java/io/hyperfoil/core/generators/TemplateStep.java
package io.hyperfoil.core.generators; import java.util.Collections; import java.util.List; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.config.StepBuilder; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.BaseStepBuilder; import io.hyperfoil.core.session.SessionFactory; public class TemplateStep implements Step { private final Pattern pattern; private final ObjectAccess toVar; public TemplateStep(Pattern pattern, ObjectAccess toVar) { this.pattern = pattern; this.toVar = toVar; } @Override public boolean invoke(Session session) { toVar.setObject(session, pattern.apply(session)); return true; } /** * Format <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a> into session * variable. */ @MetaInfServices(StepBuilder.class) @Name("template") public static class Builder extends BaseStepBuilder<Builder> { private String pattern; private String toVar; /** * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">Pattern</a> * to be encoded, e.g. <code>foo${variable}bar${another-variable}</code> * * @param pattern Template pattern. * @return Self. */ public Builder pattern(String pattern) { this.pattern = pattern; return this; } /** * Variable name to store the result. * * @param var Variable name. * @return Self. */ public Builder toVar(String var) { this.toVar = var; return this; } @Override public List<Step> build() { if (pattern == null) { throw new BenchmarkDefinitionException("Missing pattern for template."); } if (toVar == null) { throw new BenchmarkDefinitionException("Missing target var for template."); } return Collections.singletonList(new TemplateStep(new Pattern(pattern, false), SessionFactory.objectAccess(toVar))); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/generators/WeightedGenerator.java
core/src/main/java/io/hyperfoil/core/generators/WeightedGenerator.java
package io.hyperfoil.core.generators; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.ListBuilder; import io.hyperfoil.api.config.PairBuilder; public class WeightedGenerator implements Serializable { private final double[] cummulativeProbs; private final String[] items; public WeightedGenerator(double[] cummulativeProbs, String[] items) { this.cummulativeProbs = cummulativeProbs; this.items = items; } public int randomIndex() { int index; ThreadLocalRandom random = ThreadLocalRandom.current(); if (cummulativeProbs != null) { assert cummulativeProbs.length == items.length - 1; index = Arrays.binarySearch(cummulativeProbs, random.nextDouble()); if (index < 0) { return -index - 1; } else { return index; } } else { return random.nextInt(items.length); } } public String randomItem() { return items[randomIndex()]; } public String[] items() { return items; } public static class Builder<P> extends PairBuilder.OfDouble implements ListBuilder { private final P parent; private final Map<String, Double> items = new HashMap<>(); public Builder(P parent) { this.parent = parent; } public P end() { return this.parent; } @Override public void nextItem(String item) { items.compute(item, (k, value) -> value != null ? value + 1 : 1); } /** * Item as the key and weight (arbitrary floating-point number, defaults to 1.0) as the value. * * @param item Item. * @param weight Weight. */ @Override public void accept(String item, Double weight) { if (items.putIfAbsent(item, weight) != null) { throw new BenchmarkDefinitionException("Duplicate item '" + item + "' in randomItem step!"); } } public WeightedGenerator.Builder<P> add(String item, double weight) { accept(item, weight); return this; } public WeightedGenerator build() { List<String> list = new ArrayList<>(); double[] cummulativeProbs = null; if (items.isEmpty()) { throw new BenchmarkDefinitionException("No items to pick from!"); } if (items.values().stream().allMatch(v -> v == 1)) { return new WeightedGenerator(null, items.keySet().toArray(new String[0])); } cummulativeProbs = new double[items.size() - 1]; double normalizer = items.values().stream().mapToDouble(Double::doubleValue).sum(); double acc = 0; int i = 0; for (Map.Entry<String, Double> entry : items.entrySet()) { acc += entry.getValue() / normalizer; if (i < items.size() - 1) { cummulativeProbs[i++] = acc; } else { assert acc > 0.999 && acc <= 1.001; } list.add(entry.getKey()); } return new WeightedGenerator(cummulativeProbs, list.toArray(new String[0])); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/generators/IntValueProviderBuilder.java
core/src/main/java/io/hyperfoil/core/generators/IntValueProviderBuilder.java
package io.hyperfoil.core.generators; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.function.SerializableToIntFunction; public class IntValueProviderBuilder<P> implements InitFromParam<IntValueProviderBuilder<P>> { private final P parent; private final Integer defaultValue; private Integer value; private String fromVar; public IntValueProviderBuilder(P parent, Integer defaultValue) { this.parent = parent; this.defaultValue = defaultValue; } public P end() { return parent; } /** * Initialize with a constant value. * * @param param Constant value. * @return Self. */ @Override public IntValueProviderBuilder<P> init(String param) { try { value = Integer.parseInt(param.trim()); } catch (NumberFormatException e) { throw new BenchmarkDefinitionException("Cannot convert " + param + " to integer value."); } return this; } /** * Initialize with a constant value. * * @param value Constant value. * @return Self. */ public IntValueProviderBuilder<P> value(int value) { this.value = value; return this; } /** * Initialize with a value from session variable. * * @param fromVar Variable name. * @return Self. */ public IntValueProviderBuilder<P> fromVar(String fromVar) { this.fromVar = fromVar; return this; } public SerializableToIntFunction<Session> build() { if (value == null && fromVar == null && defaultValue == null) { throw new BenchmarkDefinitionException("Must set either 'value' or 'fromVar'."); } else if (value != null && fromVar != null) { throw new BenchmarkDefinitionException("Must set one of: 'value' or 'fromVar'."); } else if (fromVar != null) { ReadAccess access = SessionFactory.readAccess(fromVar); return access::getInt; } else { int unbox = value == null ? defaultValue : value; return new ConstValue(unbox); } } private int assertionValue() { if (value == null && defaultValue == null) { return 0; } else if (value != null) { return value; } else { return defaultValue; } } public int compareTo(IntValueProviderBuilder<?> other) { if (fromVar != null || other.fromVar != null) { return 0; } int v1 = assertionValue(); int v2 = other.assertionValue(); return Integer.compare(v1, v2); } private static class ConstValue implements SerializableToIntFunction<Session> { private final int value; private ConstValue(int value) { this.value = value; } @Override public int applyAsInt(Session session) { return value; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/generators/StringGeneratorImplBuilder.java
core/src/main/java/io/hyperfoil/core/generators/StringGeneratorImplBuilder.java
package io.hyperfoil.core.generators; import java.util.function.Supplier; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.function.SerializableFunction; // To be recognized as a builder by Generator the class name must end with 'Builder' /** * Generic builder for generating a string. */ public class StringGeneratorImplBuilder<T> implements StringGeneratorBuilder, InitFromParam<StringGeneratorImplBuilder<T>> { private static final Logger log = LogManager.getLogger(StringGeneratorImplBuilder.class); private final T parent; // We need the Supplier indirection to capture any Access object only during prepareBuild() or build() private Supplier<SerializableFunction<Session, String>> supplier; public StringGeneratorImplBuilder(T parent) { this.parent = parent; } /** * @param param A pattern for <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">string * interpolation</a>. * @return Self. */ @Override public StringGeneratorImplBuilder<T> init(String param) { return pattern(param); } private void set(Supplier<SerializableFunction<Session, String>> function) { if (this.supplier != null) { throw new BenchmarkDefinitionException("Specify only one of: value, var, pattern"); } this.supplier = function; } /** * String value used verbatim. * * @param value String value. * @return Self. */ public StringGeneratorImplBuilder<T> value(String value) { set(() -> session -> value); return this; } /** * Load the string from session variable. * * @param var Variable name. * @return Self. */ public StringGeneratorImplBuilder<T> fromVar(Object var) { if (var == null) { throw new BenchmarkDefinitionException("Variable must not be null"); } set(() -> { ReadAccess access = SessionFactory.readAccess(var); assert access != null; return session -> { Object value = access.getObject(session); if (value instanceof String) { return (String) value; } else { log.error("Cannot retrieve string from {}, the content is {}", var, value); return null; } }; }); return this; } /** * Use <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a> replacing session * variables. * * @param pattern Template pattern. * @return Self. */ public StringGeneratorImplBuilder<T> pattern(String pattern) { set(() -> new Pattern(pattern, false)); return this; } public T end() { return parent; } @Override public SerializableFunction<Session, String> build() { return supplier.get(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/generators/RandomIntStep.java
core/src/main/java/io/hyperfoil/core/generators/RandomIntStep.java
package io.hyperfoil.core.generators; import java.util.Collections; import java.util.List; import java.util.concurrent.ThreadLocalRandom; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.config.StepBuilder; import io.hyperfoil.api.session.IntAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.BaseStepBuilder; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.function.SerializableToIntFunction; public class RandomIntStep implements Step { private final IntAccess toVar; private final SerializableToIntFunction<Session> minInclusive; private final SerializableToIntFunction<Session> maxInclusive; public RandomIntStep(IntAccess toVar, SerializableToIntFunction<Session> minInclusive, SerializableToIntFunction<Session> maxInclusive) { this.toVar = toVar; this.minInclusive = minInclusive; this.maxInclusive = maxInclusive; } @Override public boolean invoke(Session session) { ThreadLocalRandom random = ThreadLocalRandom.current(); int r; int minInclusive = this.minInclusive.applyAsInt(session); int maxInclusive = this.maxInclusive.applyAsInt(session); if (maxInclusive == Integer.MAX_VALUE) { if (minInclusive == Integer.MIN_VALUE) { r = random.nextInt(); } else { r = random.nextInt(minInclusive - 1, maxInclusive) + 1; } } else { r = random.nextInt(minInclusive, maxInclusive + 1); } toVar.setInt(session, r); return true; } /** * Stores random (linearly distributed) integer into session variable. */ @MetaInfServices(StepBuilder.class) @Name("randomInt") public static class Builder extends BaseStepBuilder<Builder> implements InitFromParam<Builder> { private String toVar; private IntValueProviderBuilder<Builder> min = new IntValueProviderBuilder<>(this, 0); private IntValueProviderBuilder<Builder> max = new IntValueProviderBuilder<>(this, Integer.MAX_VALUE); /** * @param rangeToVar Use format `var &lt;- min .. max` * @return Self. */ @Override public Builder init(String rangeToVar) { if (rangeToVar == null) { return this; } int arrowIndex = rangeToVar.indexOf("<-"); int dotdotIndex = rangeToVar.indexOf(".."); if (arrowIndex < 0 || dotdotIndex < arrowIndex) { throw new BenchmarkDefinitionException("Expecting format var <- min .. max"); } toVar = rangeToVar.substring(0, arrowIndex).trim(); min.value(Integer.parseInt(rangeToVar.substring(arrowIndex + 2, dotdotIndex).trim())); max.value(Integer.parseInt(rangeToVar.substring(dotdotIndex + 2).trim())); return this; } /** * Variable name to store the result. * * @param var Variable name. * @return Self. */ public Builder toVar(String var) { this.toVar = var; return this; } /** * Lowest possible value (inclusive). Default is 0. * * @return Self. */ public IntValueProviderBuilder<Builder> min() { return min; } /** * Highest possible value (inclusive). Default is Integer.MAX_VALUE. * * @return Self. */ public IntValueProviderBuilder<Builder> max() { return max; } @Override public List<Step> build() { if (toVar == null || toVar.isEmpty()) { throw new BenchmarkDefinitionException("Missing target var."); } if (min.compareTo(max) > 0) { throw new BenchmarkDefinitionException("min must be less than max"); } return Collections.singletonList(new RandomIntStep(SessionFactory.intAccess(toVar), min.build(), max.build())); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/generators/RandomFileStep.java
core/src/main/java/io/hyperfoil/core/generators/RandomFileStep.java
package io.hyperfoil.core.generators; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkData; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Locator; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.config.StepBuilder; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.impl.Util; public class RandomFileStep implements Step { private final WeightedGenerator generator; private final byte[][] fileBytes; private final ObjectAccess toVar; private final ObjectAccess filenameVar; public RandomFileStep(WeightedGenerator generator, byte[][] fileBytes, ObjectAccess toVar, ObjectAccess filenameVar) { this.generator = generator; this.fileBytes = fileBytes; this.toVar = toVar; this.filenameVar = filenameVar; } @Override public boolean invoke(Session session) { int index = generator.randomIndex(); toVar.setObject(session, fileBytes[index]); if (filenameVar != null) { filenameVar.setObject(session, generator.items()[index]); } return true; } /** * Reads bytes from a randomly chosen file into a variable. <br> * Two formats are supported: <br> * Example 1 - without weights: * * <pre> * toVar: myVar * files: * - /path/to/file1.txt * - file2_relative_to_benchmark.txt * </pre> * <p> * Example 2 - with weights (the second file will be returned twice as often): * * <pre> * toVar: myVar * files: * /path/to/file1.txt: 1 * file2_relative_to_benchmark.txt: 2 * </pre> */ @MetaInfServices(StepBuilder.class) @Name("randomFile") public static class Builder implements StepBuilder<Builder> { private String toVar; private WeightedGenerator.Builder<Builder> weighted = new WeightedGenerator.Builder<>(this); private String filenameVar; /** * Potentially weighted list of files to choose from. * * @return Builder. */ public WeightedGenerator.Builder<Builder> files() { return weighted; } /** * Variable where the chosen byte array should be stored. * * @param var Variable name. * @return Self. */ public Builder toVar(String var) { this.toVar = var; return this; } /** * Optional variable to store the filename of the random file. * * @param var Variable name. * @return Self. */ public Builder filenameVar(String var) { this.filenameVar = var; return this; } @Override public List<Step> build() { WeightedGenerator generator = weighted.build(); BenchmarkData data = Locator.current().benchmark().data(); List<byte[]> fileBytes = new ArrayList<>(); for (String file : generator.items()) { try { fileBytes.add(Util.toByteArray(data.readFile(file))); } catch (IOException e) { throw new BenchmarkDefinitionException("Cannot read bytes from file " + file); } } return Collections.singletonList(new RandomFileStep(generator, fileBytes.toArray(new byte[0][]), SessionFactory.objectAccess(toVar), SessionFactory.objectAccess(filenameVar))); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/generators/ActionsTransformer.java
core/src/main/java/io/hyperfoil/core/generators/ActionsTransformer.java
package io.hyperfoil.core.generators; import java.util.ArrayList; import java.util.List; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.processor.Transformer; import io.hyperfoil.api.session.Action; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.ServiceLoadedBuilderProvider; import io.hyperfoil.core.data.DataFormat; import io.hyperfoil.core.handlers.DefragTransformer; import io.hyperfoil.core.session.SessionFactory; import io.netty.buffer.ByteBuf; public class ActionsTransformer implements Transformer { private final ObjectAccess var; private final DataFormat format; private final Action[] actions; private final Pattern pattern; public ActionsTransformer(ObjectAccess var, DataFormat format, Action[] actions, Pattern pattern) { this.var = var; this.format = format; this.actions = actions; this.pattern = pattern; } @Override public void transform(Session session, ByteBuf in, int offset, int length, boolean lastFragment, ByteBuf out) { assert lastFragment; var.setObject(session, format.convert(in, offset, length)); for (Action action : actions) { action.run(session); } pattern.accept(session, out); } /** * This transformer stores the (defragmented) input into a variable, using requested format. * After that it executes all the actions and fetches transformed value using the pattern. */ @MetaInfServices(Transformer.Builder.class) @Name("actions") public static class Builder implements Transformer.Builder { private String var; private DataFormat format = DataFormat.STRING; private String pattern; private List<Action.Builder> actions = new ArrayList<>(); /** * Variable used as the intermediate storage for the data. * * @param var Variable name. * @return Self. */ public Builder var(String var) { this.var = var; return this; } /** * Format into which should this transformer convert the buffers before storing. Default is <code>STRING</code>. * * @param format Data format. * @return Self. */ public Builder format(DataFormat format) { this.format = format; return this; } /** * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">Pattern</a> * to use when fetching the transformed value. * * @param pattern Pattern replacing `${myVar}` by the variable value. * @return Self. */ public Builder pattern(String pattern) { this.pattern = pattern; return this; } private Builder actions(List<Action.Builder> actions) { this.actions = actions; return this; } /** * Actions to be executed. * * @return Builder. */ public ServiceLoadedBuilderProvider<Action.Builder> actions() { return new ServiceLoadedBuilderProvider<>(Action.Builder.class, actions::add); } @Override public Transformer build(boolean fragmented) { if (var == null) { throw new BenchmarkDefinitionException("Missing variable name"); } else if (actions.isEmpty()) { throw new BenchmarkDefinitionException("No actions; use `store` processor instead."); } ActionsTransformer transformer = new ActionsTransformer(SessionFactory.objectAccess(var), format, actions.stream().map(Action.Builder::build).toArray(Action[]::new), new Pattern(pattern, false)); return fragmented ? transformer : new DefragTransformer(transformer); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/generators/RandomCsvRowStep.java
core/src/main/java/io/hyperfoil/core/generators/RandomCsvRowStep.java
package io.hyperfoil.core.generators; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.Objects; import java.util.concurrent.ThreadLocalRandom; import java.util.function.IntUnaryOperator; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Locator; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.PairBuilder; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.config.StepBuilder; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.BaseStepBuilder; import io.hyperfoil.core.session.SessionFactory; /** * A class that will initialise, build and randomly select a single row of data. * The row is exposed as columns. */ public class RandomCsvRowStep implements Step { private final String[][] rows; private final ObjectAccess[] columnVars; // Use just for testing private final transient IntUnaryOperator rowSelector; public RandomCsvRowStep(String[][] rows, ObjectAccess[] columnVars, IntUnaryOperator rowSelector) { this.rows = rows; this.columnVars = columnVars; this.rowSelector = rowSelector; } // Visible for testing String[][] rows() { return rows; } // Visible for testing IntUnaryOperator rowSelector() { return rowSelector; } @Override public boolean invoke(Session session) { if (rows.length == 0) { throw new RuntimeException("No rows available - was the CSV file empty?"); } // columns provided by csv final var rowSelector = this.rowSelector; final int rndRow; if (rowSelector == null) { rndRow = ThreadLocalRandom.current().nextInt(rows.length); } else { rndRow = rowSelector.applyAsInt(rows.length); } final var row = rows[rndRow]; final var columnVars = this.columnVars; for (int i = 0; i < columnVars.length; i++) { columnVars[i].setObject(session, row[i]); } return true; } /** * Stores random row from a CSV-formatted file to variables. */ @MetaInfServices(StepBuilder.class) @Name("randomCsvRow") public static class Builder extends BaseStepBuilder<Builder> { private String file; private boolean skipComments; private char separator = ','; private final List<String> builderColumns = new ArrayList<>(); private transient IntUnaryOperator customRowSelector = null; @Override public List<Step> build() { int[] srcIndex = new int[(int) builderColumns.stream().filter(Objects::nonNull).count()]; int next = 0; for (int i = 0; i < builderColumns.size(); ++i) { if (builderColumns.get(i) != null) { srcIndex[next++] = i; } } assert next == srcIndex.length; try (InputStream inputStream = Locator.current().benchmark().data().readFile(file)) { BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); ArrayList<String[]> records = new ArrayList<>(); String line; ArrayList<String> currentRecord = new ArrayList<>(); StringBuilder sb = new StringBuilder(); boolean quoted = false; boolean maybeClosingQuote = false; int lineNumber = 1; while ((line = reader.readLine()) != null) { if (!quoted && skipComments && line.stripLeading().startsWith("#")) { continue; } for (int i = 0; i < line.length(); ++i) { char c = line.charAt(i); if (!quoted) { if (c == separator) { currentRecord.add(sb.toString()); sb.setLength(0); } else if (c == '"') { if (sb.length() != 0) { throw new BenchmarkDefinitionException("The CSV file " + file + " is invalid; line " + lineNumber + " uses quote but it's quoting correctly (check preceding whitespaces?)"); } quoted = true; } else { sb.append(c); } } else { if (i == 0) { assert lineNumber > 1; sb.append('\n'); } if (c == '"') { if (maybeClosingQuote) { sb.append(c); // quoted quote maybeClosingQuote = false; } else { maybeClosingQuote = true; } } else if (maybeClosingQuote) { quoted = false; maybeClosingQuote = false; if (c == separator) { currentRecord.add(sb.toString()); sb.setLength(0); } else { throw new BenchmarkDefinitionException("The CSV file " + file + " is invalid; line " + lineNumber + " uses quote but it's quoting correctly (check characters after?)"); } } else { sb.append(c); } } } if (maybeClosingQuote) { quoted = false; maybeClosingQuote = false; } if (!quoted) { currentRecord.add(sb.toString()); sb.setLength(0); String[] arr = new String[srcIndex.length]; Arrays.setAll(arr, i -> srcIndex[i] < currentRecord.size() ? currentRecord.get(srcIndex[i]) : null); currentRecord.clear(); records.add(arr); } ++lineNumber; } String[][] rows = records.toArray(new String[0][]); // We won't throw an error even if the CSV is empty - this can happen during edit in CLI when we expect // to reuse the data on server side. ObjectAccess[] columnVars = builderColumns.stream().filter(Objects::nonNull).map(SessionFactory::objectAccess) .toArray(ObjectAccess[]::new); return Collections.singletonList(new RandomCsvRowStep(rows, columnVars, customRowSelector)); } catch (IOException ioe) { throw new BenchmarkDefinitionException("Failed to read file " + file, ioe); } } // Visible For Testing Builder customSelector(IntUnaryOperator selector) { this.customRowSelector = Objects.requireNonNull(selector); return this; } /** * Defines mapping from columns to session variables. * * @return Builder. */ public ColumnsBuilder columns() { return new ColumnsBuilder(); } /** * Path to the CSV file that should be loaded. * * @param file Path to file. * @return Self. */ public Builder file(String file) { this.file = file; return this; } /** * Skip lines starting with character '#'. By default set to false. * * @param skipComments Skip? * @return Self. */ public Builder skipComments(boolean skipComments) { this.skipComments = skipComments; return this; } /** * DEPRECATED. Quotes are removed automatically. * * @param removeQuotes Remove? * @return Self. * @deprecated */ @Deprecated public Builder removeQuotes(@SuppressWarnings("unused") boolean removeQuotes) { return this; } /** * Set character used for column separation. By default it is comma (<code>,</code>). * * @param separator Separator character. * @return Self. */ public Builder separator(char separator) { this.separator = separator; return this; } public class ColumnsBuilder extends PairBuilder.OfString { /** * Use 0-based column as the key and variable name as the value. * * @param position 0-based column number. * @param columnVar Variable name. */ @Override public void accept(String position, String columnVar) { int pos = Integer.parseInt(position); if (pos < 0) { throw new BenchmarkDefinitionException("Negative column index is not supported."); } while (pos >= builderColumns.size()) { builderColumns.add(null); } String prev = builderColumns.set(pos, columnVar); if (prev != null) { throw new BenchmarkDefinitionException( "Column " + pos + " is already mapped to '" + prev + "', don't map to '" + columnVar + "'"); } } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/generators/Pattern.java
core/src/main/java/io/hyperfoil/core/generators/Pattern.java
package io.hyperfoil.core.generators; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Base64; import java.util.List; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.Visitor; import io.hyperfoil.api.connection.Connection; import io.hyperfoil.api.processor.Transformer; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.function.SerializableBiConsumer; import io.hyperfoil.function.SerializableBiFunction; import io.hyperfoil.function.SerializableFunction; import io.hyperfoil.impl.Util; import io.netty.buffer.ByteBuf; public class Pattern implements SerializableFunction<Session, String>, SerializableBiConsumer<Session, ByteBuf>, Transformer { private static final int VAR_LENGTH_ESTIMATE = 32; private static final String REPLACE = "replace"; private final Component[] components; @Visitor.Ignore private int lengthEstimate; private final boolean urlEncode; public Pattern(String str, boolean urlEncode) { this(str, urlEncode, false); } public Pattern(String str, boolean urlEncode, boolean allowUnset) { this.urlEncode = urlEncode; List<Component> components = new ArrayList<>(); int last = 0, lastSearch = 0; for (;;) { int openPar = str.indexOf("${", lastSearch); if (openPar < 0) { String substring = str.substring(last); if (!str.isEmpty()) { components.add(new StringComponent(substring.replaceAll("\\$\\$\\{", "\\${"))); lengthEstimate += substring.length(); } break; } else { if (openPar > 0 && str.charAt(openPar - 1) == '$') { // $${...} = escape syntax lastSearch = openPar + 1; continue; } String substring = str.substring(last, openPar); components.add(new StringComponent(substring.replaceAll("\\$\\$\\{", "\\${"))); lengthEstimate += substring.length() + VAR_LENGTH_ESTIMATE; int closePar = str.indexOf("}", openPar); int colon = str.indexOf(":", openPar); if (colon >= 0 && colon < closePar) { String format = str.substring(openPar + 2, colon).trim(); ReadAccess key = SessionFactory.readAccess(str.substring(colon + 1, closePar).trim()); // TODO: we can't pre-allocate formatters here but we could cache them in the session // TODO: find a better place for this hack if (format.equalsIgnoreCase("urlencode")) { if (urlEncode) { throw new BenchmarkDefinitionException("It seems you're trying to URL-encode value twice."); } components.add(new VarComponent(key, allowUnset, Pattern::urlEncode)); // TODO: More efficient encoding/decoding: we're converting object to string, then to byte array and then allocating another string } else if (format.equalsIgnoreCase("base64encode")) { components.add(new VarComponent(key, allowUnset, s -> Base64.getEncoder().encodeToString(s.getBytes(StandardCharsets.UTF_8)))); } else if (format.equalsIgnoreCase("base64decode")) { components.add(new VarComponent(key, allowUnset, s -> new String(Base64.getDecoder().decode(s), StandardCharsets.UTF_8))); } else if (format.startsWith(REPLACE)) { if (format.length() == REPLACE.length()) { throw new BenchmarkDefinitionException(wrongReplaceSyntax(str, format)); } char separator = format.charAt(REPLACE.length()); int regexpEnd = format.indexOf(separator, REPLACE.length() + 1); int replacementEnd = format.indexOf(separator, regexpEnd + 1); if (regexpEnd < 0 || replacementEnd < 0) { throw new BenchmarkDefinitionException(wrongReplaceSyntax(str, format)); } java.util.regex.Pattern regex = java.util.regex.Pattern .compile(format.substring(REPLACE.length() + 1, regexpEnd)); String replacement = format.substring(regexpEnd + 1, replacementEnd); boolean all = false; if (format.length() > replacementEnd + 1) { String flags = format.substring(replacementEnd + 1); if ("g".equals(flags)) { all = true; } else { throw new BenchmarkDefinitionException( "Unknown flags '" + flags + "' in replace expression in '" + str + "'"); } } if (all) { components.add(new VarComponent(key, allowUnset, value -> regex.matcher(value).replaceAll(replacement))); } else { components.add(new VarComponent(key, allowUnset, value -> regex.matcher(value).replaceFirst(replacement))); } } else if (format.endsWith("d") || format.endsWith("o") || format.endsWith("x") || format.endsWith("X")) { components.add(new FormatIntComponent(format, key)); } else { throw new IllegalArgumentException("Cannot use format string '" + format + "', only integers are supported"); } } else if (closePar < 0) { throw new BenchmarkDefinitionException("Missing closing parentheses (}) in '" + str + "'"); } else { ReadAccess key = SessionFactory.readAccess(str.substring(openPar + 2, closePar).trim()); components.add(new VarComponent(key, allowUnset, urlEncode ? Pattern::urlEncode : null)); } lastSearch = last = closePar + 1; } } this.components = components.toArray(new Component[0]); } private String wrongReplaceSyntax(String pattern, String expression) { return "Wrong replace syntax: use ${replace/regexp/replacement/flags:my-variable} " + "where '/' can be any character. The offending replace expression was '" + expression + "' in '" + pattern + "'."; } private static String urlEncode(String string) { try { return URLEncoder.encode(string, StandardCharsets.UTF_8.name()); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException(e); } } @Override public String apply(Session session) { if (components.length == 1 && components[0] instanceof StringComponent) { return ((StringComponent) components[0]).substring; } StringBuilder sb = new StringBuilder(lengthEstimate); for (Component c : components) { c.accept(session, sb); } return sb.toString(); } @Override public void accept(Session session, ByteBuf byteBuf) { for (Component c : components) { c.accept(session, byteBuf); } } @Override public void transform(Session session, ByteBuf in, int offset, int length, boolean lastFragment, ByteBuf out) { if (lastFragment) { accept(session, out); } } public Generator generator() { return new Generator(this); } interface Component extends Serializable { void accept(Session session, StringBuilder sb); void accept(Session session, ByteBuf buf); } private static class Generator implements SerializableBiFunction<Session, Connection, ByteBuf> { private final Pattern pattern; private Generator(Pattern pattern) { this.pattern = pattern; } @Override public ByteBuf apply(Session session, Connection connection) { ByteBuf buffer = connection.context().alloc().buffer(pattern.lengthEstimate); pattern.accept(session, buffer); return buffer; } } private class StringComponent implements Component { private final String substring; @Visitor.Ignore private final byte[] bytes; StringComponent(String substring) { if (urlEncode) { substring = urlEncode(substring); } this.substring = substring; this.bytes = substring.getBytes(StandardCharsets.UTF_8); } @Override public void accept(Session s, StringBuilder sb) { sb.append(substring); } @Override public void accept(Session session, ByteBuf buf) { buf.writeBytes(bytes); } } private class FormatIntComponent implements Component { private final String format; private final ReadAccess key; FormatIntComponent(String format, ReadAccess key) { this.format = format; this.key = key; } private String string(Session session) { return String.format(this.format, key.getInt(session)); } @Override public void accept(Session s, StringBuilder sb) { String str = string(s); sb.append(urlEncode ? urlEncode(str) : str); } @Override public void accept(Session session, ByteBuf buf) { String str = string(session); if (urlEncode) { Util.urlEncode(str, buf); } else { Util.string2byteBuf(str, buf); } } } private static class VarComponent implements Component { private final ReadAccess key; private final boolean allowUnset; private final SerializableFunction<String, String> transform; VarComponent(ReadAccess key, boolean allowUnset, SerializableFunction<String, String> transform) { this.key = key; this.allowUnset = allowUnset; this.transform = transform; } @Override public void accept(Session session, StringBuilder sb) { Session.Var var = key.getVar(session); if (!var.isSet()) { if (allowUnset) { sb.append("<not set>"); } else { throw new IllegalArgumentException("Variable " + key + " is not set!"); } } else { switch (var.type()) { case OBJECT: String str = Util.prettyPrintObject(var.objectValue(session)); if (transform != null) { str = transform.apply(str); } sb.append(str); break; case INTEGER: sb.append(var.intValue(session)); break; default: throw new IllegalArgumentException("Unknown var type: " + var); } } } @Override public void accept(Session session, ByteBuf buf) { Session.Var var = key.getVar(session); if (!var.isSet()) { throw new IllegalArgumentException("Variable " + key + " is not set!"); } else { switch (var.type()) { case OBJECT: Object o = var.objectValue(session); if (o != null) { CharSequence str = o instanceof CharSequence ? (CharSequence) o : Util.prettyPrintObject(o); if (transform != null) { str = transform.apply(str.toString()); } Util.string2byteBuf(str, buf); } else { Util.string2byteBuf("null", buf); } break; case INTEGER: Util.intAsText2byteBuf(var.intValue(session), buf); break; default: throw new IllegalArgumentException("Unknown var type: " + var); } } } } /** * Use <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a> replacing session * variables. */ @MetaInfServices(Transformer.Builder.class) @Name("pattern") public static class TransformerBuilder implements Transformer.Builder, InitFromParam<TransformerBuilder> { public String pattern; /** * Use <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a> replacing * session variables. * * @param param The pattern formatting string. * @return Self. */ @Override public TransformerBuilder init(String param) { return pattern(param); } /** * Use <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a> replacing * session variables. * * @param pattern The pattern formatting string. * @return Self. */ public TransformerBuilder pattern(String pattern) { this.pattern = pattern; return this; } @Override public Pattern build(boolean fragmented) { return new Pattern(pattern, false); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/generators/RandomUUIDStep.java
core/src/main/java/io/hyperfoil/core/generators/RandomUUIDStep.java
package io.hyperfoil.core.generators; import java.util.Collections; import java.util.List; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.config.StepBuilder; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.BaseStepBuilder; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.core.util.LongFastUUID; public class RandomUUIDStep implements Step { private final ObjectAccess toVar; public RandomUUIDStep(ObjectAccess toVar) { this.toVar = toVar; } @Override public boolean invoke(Session session) { toVar.setObject(session, LongFastUUID.randomUUID()); return true; } /** * Stores random string into session variable based on the UUID generator. */ @MetaInfServices(StepBuilder.class) @Name("randomUUID") public static class Builder extends BaseStepBuilder<Builder> implements InitFromParam<Builder> { private String toVar; /** * @param toVar Variable name to store the result. * @return Self. */ @Override public Builder init(String toVar) { return toVar(toVar); } /** * Variable name to store the result. * * @param var Variable name. * @return Self. */ public Builder toVar(String var) { this.toVar = var; return this; } @Override public List<Step> build() { if (toVar == null || toVar.isEmpty()) { throw new BenchmarkDefinitionException("Missing target var."); } return Collections.singletonList(new RandomUUIDStep(SessionFactory.objectAccess(toVar))); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/api/PluginRunData.java
core/src/main/java/io/hyperfoil/core/api/PluginRunData.java
package io.hyperfoil.core.api; import java.time.Clock; import java.util.concurrent.Callable; import java.util.function.Consumer; import java.util.function.Function; import io.hyperfoil.api.config.Scenario; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.impl.ConnectionStatsConsumer; import io.vertx.core.Future; public interface PluginRunData { void initSession(Session session, int executorId, Scenario scenario, Clock clock); /** * Plugin should create any connections that it requires to properly perform the configured benchmark scenario. * This method should never block.If a call has operations that are non blocking it should register those as * <p> * Future objects to the provided <b>promiseCollector</b> so that the Hyperfoil framework can be notified when * the connections have all been established. * <p> * If the plugin cannot open a connection without blocking it can invoke the desired code in the provided * <b>blockingHandler</b> which will perform the operation on a blocking thread to prevent the method from blocking. * The future(s) returned from the handler should then be registered with the <b>promiseCollector</b>. * * @param blockingHandler Handler that can be used to run blocking code, returning a Future that must be registered * @param promiseCollector Collector to notify invoker that there outstanding operations that will complete at some * point in the future. */ void openConnections(Function<Callable<Void>, Future<Void>> blockingHandler, Consumer<Future<Void>> promiseCollector); void listConnections(Consumer<String> connectionCollector); void visitConnectionStats(ConnectionStatsConsumer consumer); void shutdown(); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/api/Plugin.java
core/src/main/java/io/hyperfoil/core/api/Plugin.java
package io.hyperfoil.core.api; import java.util.ServiceLoader; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.BenchmarkBuilder; import io.hyperfoil.api.config.PluginConfig; import io.hyperfoil.core.parser.ErgonomicsParser; import io.hyperfoil.core.parser.Parser; import io.netty.channel.EventLoop; public interface Plugin { static Plugin lookup(PluginConfig config) { return ServiceLoader.load(Plugin.class).stream() .map(ServiceLoader.Provider::get) .filter(p -> p.configClass() == config.getClass()) .findFirst() .orElseThrow(() -> new IllegalStateException("Missing plugin for config " + config.getClass().getName())); } Class<? extends PluginConfig> configClass(); String name(); Parser<BenchmarkBuilder> parser(); void enhanceErgonomics(ErgonomicsParser ergonomicsParser); PluginRunData createRunData(Benchmark benchmark, EventLoop[] executors, int agentId); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/metric/ProvidedMetricSelector.java
core/src/main/java/io/hyperfoil/core/metric/ProvidedMetricSelector.java
package io.hyperfoil.core.metric; public class ProvidedMetricSelector implements MetricSelector { private String name; public ProvidedMetricSelector(String name) { this.name = name; } @Override public String apply(String authority, String path) { return name; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/metric/MetricSelector.java
core/src/main/java/io/hyperfoil/core/metric/MetricSelector.java
package io.hyperfoil.core.metric; import io.hyperfoil.function.SerializableBiFunction; public interface MetricSelector extends SerializableBiFunction<String, String, String> { }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/metric/PathMetricSelector.java
core/src/main/java/io/hyperfoil/core/metric/PathMetricSelector.java
package io.hyperfoil.core.metric; import java.util.ArrayList; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import io.hyperfoil.api.config.ListBuilder; import io.hyperfoil.api.config.Visitor; import io.hyperfoil.function.SerializableFunction; /** * Allows categorizing request statistics into metrics based on the request path. The expressions are evaluated * in the order as provided in the list. * Use one of: * <ul> * <li><code>regexp -&gt; replacement</code>, e.g. <code>([^?]*)(\?.*)? -&gt; $1</code> to drop the query part. * <li><code>regexp</code> (don't do any replaces and use the full path), e.g. <code>.*.jpg</code> * <li><code>-&gt; name</code> (metric applied if none of the previous expressions match). * </ul> */ public class PathMetricSelector implements ListBuilder, MetricSelector { public List<SerializableFunction<String, String>> tests = new ArrayList<>(); @Override public void nextItem(String item) { item = item.trim(); int arrow = item.indexOf("->"); if (arrow < 0) { Pattern pattern = Pattern.compile(item); tests.add(new SimpleMatch(pattern)); } else if (arrow == 0) { String replacement = item.substring(2).trim(); tests.add(new Fallback(replacement)); } else { Pattern pattern = Pattern.compile(item.substring(0, arrow).trim()); String replacement = item.substring(arrow + 2).trim(); tests.add(new ReplaceMatch(pattern, replacement)); } } @Override public String apply(String authority, String path) { String combined = authority != null ? authority + path : path; for (SerializableFunction<String, String> test : tests) { String result = test.apply(combined); if (result != null) { return result; } } return null; } private static class SimpleMatch implements SerializableFunction<String, String> { @Visitor.Invoke(method = "pattern") private final Pattern pattern; SimpleMatch(Pattern pattern) { this.pattern = pattern; } public String pattern() { return pattern.pattern(); } @Override public String apply(String path) { return pattern.matcher(path).matches() ? path : null; } } private static class Fallback implements SerializableFunction<String, String> { private final String metric; Fallback(String metric) { this.metric = metric; } @Override public String apply(String path) { return metric; } } private static class ReplaceMatch implements SerializableFunction<String, String> { @Visitor.Invoke(method = "pattern") private final Pattern pattern; private final String replacement; ReplaceMatch(Pattern pattern, String replacement) { this.pattern = pattern; this.replacement = replacement; } public String pattern() { return pattern.pattern(); } @Override public String apply(String path) { Matcher matcher = pattern.matcher(path); if (matcher.matches()) { return matcher.replaceFirst(replacement); } else { return null; } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/metric/AuthorityAndPathMetric.java
core/src/main/java/io/hyperfoil/core/metric/AuthorityAndPathMetric.java
package io.hyperfoil.core.metric; public class AuthorityAndPathMetric implements MetricSelector { @Override public String apply(String authority, String path) { return authority == null ? path : authority + path; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/ObjectVar.java
core/src/main/java/io/hyperfoil/core/session/ObjectVar.java
package io.hyperfoil.core.session; import io.hyperfoil.api.session.Session; public class ObjectVar implements Session.Var { boolean set; Object value; public static ObjectVar[] newArray(Session session, int size) { ObjectVar[] array = new ObjectVar[size]; for (int i = 0; i < array.length; ++i) array[i] = new ObjectVar((SessionImpl) session); return array; } ObjectVar(SessionImpl session) { session.registerVar(this); } @Override public Session.VarType type() { return Session.VarType.OBJECT; } @Override public Object objectValue(Session session) { return value; } @Override public boolean isSet() { return set; } @Override public void unset() { set = false; } public void set(Object value) { this.value = value; this.set = true; } @Override public String toString() { if (set) { return "(object:" + value + ")"; } else { return "(object:unset)"; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/SimpleObjectAccess.java
core/src/main/java/io/hyperfoil/core/session/SimpleObjectAccess.java
package io.hyperfoil.core.session; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.impl.Util; class SimpleObjectAccess extends SimpleReadAccess implements ObjectAccess { SimpleObjectAccess(Object key) { super(key); } @Override public Session.Var createVar(Session session, Session.Var existing) { if (existing == null) { return new ObjectVar((SessionImpl) session); } else if (existing instanceof ObjectVar) { return existing; } else { throw new BenchmarkDefinitionException( "Variable " + key + " should hold an object but it is defined to hold an integer elsewhere."); } } @Override public void setObject(Session session, Object value) { SessionImpl impl = (SessionImpl) session; if (trace) { log.trace("#{} {} <- {}", impl.uniqueId(), key, Util.prettyPrintObject(value)); } ObjectVar var = impl.getVar(index); var.value = value; var.set = true; } @Override public Object activate(Session session) { SessionImpl impl = (SessionImpl) session; ObjectVar var = impl.getVar(index); var.set = true; return var.objectValue(session); } @Override public void unset(Session session) { SessionImpl impl = (SessionImpl) session; impl.getVar(index).unset(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/SequenceScopedReadAccess.java
core/src/main/java/io/hyperfoil/core/session/SequenceScopedReadAccess.java
package io.hyperfoil.core.session; import java.lang.reflect.Array; import java.util.List; import io.hyperfoil.api.session.Session; class SequenceScopedReadAccess extends BaseAccess { protected final int maxConcurrency; SequenceScopedReadAccess(Object key, int maxConcurrency) { super(key); this.maxConcurrency = maxConcurrency; } @Override public boolean isSet(Session session) { SessionImpl impl = (SessionImpl) session; ObjectVar var = impl.getVar(index); if (!var.isSet()) { return false; } Object o = getItemFromVar(session, var); if (o instanceof Session.Var) { return ((Session.Var) o).isSet(); } else { int index = session.currentSequence().index(); throw new IllegalStateException("Variable " + key + "[" + index + "] should contain Session.Var but contains " + o); } } @Override public Object getObject(Session session) { Object o = getItem(session); if (o instanceof Session.Var) { Session.Var ov = (Session.Var) o; if (!ov.isSet()) { int index = session.currentSequence().index(); throw new IllegalStateException("Variable " + key + "[" + index + "] was not set yet!"); } return ov.objectValue(session); } else { int index = session.currentSequence().index(); throw new IllegalStateException("Variable " + key + "[" + index + "] should contain ObjectVar but contains " + o); } } @Override public int getInt(Session session) { Object o = getItem(session); if (o instanceof IntVar) { IntVar iv = (IntVar) o; if (!iv.isSet()) { int index = session.currentSequence().index(); throw new IllegalStateException("Variable " + key + "[" + index + "] was not set yet!"); } return iv.intValue(session); } else { int index = session.currentSequence().index(); throw new IllegalStateException("Variable " + key + "[" + index + "] should contain IntVar but contains " + o); } } @Override public Session.Var getVar(Session session) { Object o = getItem(session); if (o instanceof Session.Var) { return (Session.Var) o; } else { int index = session.currentSequence().index(); throw new IllegalStateException("Variable " + key + "[" + index + "] should contain Session.Var but contains " + o); } } @Override public boolean isSequenceScoped() { return true; } @Override public String toString() { return key + "[.]"; } protected Object getItem(Session session) { SessionImpl impl = (SessionImpl) session; ObjectVar var = impl.getVar(index); if (!var.isSet()) { throw new IllegalStateException("Variable " + key + " is not set!"); } return getItemFromVar(session, var); } protected Object getItemFromVar(Session session, ObjectVar var) { Object collection = var.objectValue(session); if (collection == null) { throw new IllegalStateException("Variable " + key + " is null!"); } int index = session.currentSequence().index(); if (index >= maxConcurrency) { throw new IllegalStateException( "Variable " + key + " reads item at index " + index + " but the maximum concurrency is " + maxConcurrency); } if (collection.getClass().isArray()) { return Array.get(collection, index); } else if (collection instanceof List) { return ((List<?>) collection).get(index); } else { throw new IllegalStateException("Unknown type to access by index: " + collection); } } protected ObjectVar getVarToSet(Session session) { SessionImpl impl = (SessionImpl) session; Session.Var var = impl.getVar(index); if (var instanceof ObjectVar) { ObjectVar ov = (ObjectVar) var; ov.set = true; return ov; } else { throw new IllegalStateException("Variable " + key + " does not hold an object variable (cannot hold array)."); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/package-info.java
core/src/main/java/io/hyperfoil/core/session/package-info.java
/** * <h2>Design</h2> * <p> * There are two main components: * <ul> * <li>{@link io.hyperfoil.api.config.Sequence Sequence templates} - instructions 'what to do' * <li>Session (execution context) holds any state, including current state of the state machine and variables * </ul> * <h3>Memory allocation</h3> * <p> * In order to keep object allocations at minimum we're expected to know all variables in advance and pre-allocate * these in the Session object. During consecutive repetitions of the user scenario * the {@link io.hyperfoil.core.session.SessionImpl} is {@link io.hyperfoil.core.session.SessionImpl#reset()} * which does not release the memory. * <p> * Any memory required by handlers must be known ahead and these should implement * the {@link io.hyperfoil.api.session.ResourceUtilizer} interface to register itselves. The reservation is invoked * once when the session is created through {@link io.hyperfoil.api.config.Sequence#reserve(Session)} * which in turn calls this on all {@link io.hyperfoil.api.config.Step steps} and these call the * {@link io.hyperfoil.api.processor.Processor processors} or any other handlers. * * <h3>Execution</h3> * <p> * After the session is constructed or reset you should create {@link io.hyperfoil.api.session.SequenceInstance sequence * instances} * from the {@link io.hyperfoil.api.config.Sequence templates} and subsequently * {@link io.hyperfoil.core.session.SessionImpl#startSequence(java.lang.String, boolean, io.hyperfoil.api.session.Session.ConcurrencyPolicy) * start} * them in the session. Upon {@link io.hyperfoil.core.session.SessionImpl#runSession()} the session tries to invoke all enabled * sequence instances; some of the enabled sequences may be blocked because of missing data dependency. * <p> * The sequence consists of several {@link io.hyperfoil.api.config.Step steps}, each of which may have some * data dependency. Therefore the sequence may be blocked in the middle. Other enabled sequence may be still invoked * as soon as its dependencies are satisfied. Each step can enable further sequences. * <p> * The execution of sequence cannot be forked but it can be terminated by calling * {@link io.hyperfoil.core.session.SessionImpl#currentSequence(SequenceInstance)} * with <code>null</code> argument - {@link io.hyperfoil.core.steps.BreakSequenceStep} is an example of that. * <p> * Execution is terminated when there are no enabled sequences in the session. * * <h3>Variables</h3> * <p> * The {@link io.hyperfoil.api.session.Session} is provided as a parameter to most calls and stores all state of the scenario. * The state is operated using "accessors"; these can be retrieved from * {@link io.hyperfoil.core.session.SessionFactory#readAccess(java.lang.Object)}, * {@link io.hyperfoil.core.session.SessionFactory#objectAccess(java.lang.Object)}, * {@link io.hyperfoil.core.session.SessionFactory#intAccess(java.lang.Object)}, and similar methods. * counterparts. * <p> * Initially all variables are in undefined state; reading such variable is considered an error. The unset/set state * forms the basis of data-dependencies mentioned earlier: when a step requires the variable to be defined, you should * declare that through {@link io.hyperfoil.core.steps.DependencyStep}. * <p> * Simple variables are scalar, these are useful for scenario-scoped data. Other variables are scoped for particular * {@link io.hyperfoil.api.session.SequenceInstance}; these should be implemented as arrays (or collections) with * a limited size equal to the number of instances. When a Step/Processor needs to address sequence-scoped data * it fetches its index through * {@link io.hyperfoil.core.session.SessionImpl#currentSequence()}.{@link io.hyperfoil.api.session.SequenceInstance#index() * index()}. * <p> * The choice of index is up to the Step that creates the new sequences. Two concurrently enabled sequences may share * the same index, but in that case these should not use the same variable names for sequence-scoped data. * * <h3>Threading model</h3> * <p> * There's no internal synchronization of anything; we rely on the event-loop model. * Each {@link io.hyperfoil.api.session.Session session} is tied to a single-threaded {@link io.netty.channel.EventLoop event * loop}. */ package io.hyperfoil.core.session; import io.hyperfoil.api.session.SequenceInstance; import io.hyperfoil.api.session.Session;
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/AgentDataImpl.java
core/src/main/java/io/hyperfoil/core/session/AgentDataImpl.java
package io.hyperfoil.core.session; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import io.hyperfoil.api.BenchmarkExecutionException; import io.hyperfoil.api.session.AgentData; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.Session; public class AgentDataImpl implements AgentData { private ConcurrentMap<String, Object> map = new ConcurrentHashMap<>(); @Override public void push(Session session, String name, Object obj) { if (map.putIfAbsent(name, obj) != null) { session.fail(new BenchmarkExecutionException("Trying to push global data '" + name + "' second time.")); } } @Override public void pull(Session session, String name, ObjectAccess access) { Object obj = map.get(name); if (obj == null) { session.fail(new BenchmarkExecutionException("Trying to pull global data '" + name + "' but it is not defined; maybe you need to synchronize phases with 'startAfterStrict'?")); } access.setObject(session, obj); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/SequenceScopedIntAccess.java
core/src/main/java/io/hyperfoil/core/session/SequenceScopedIntAccess.java
package io.hyperfoil.core.session; import java.util.Arrays; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.session.IntAccess; import io.hyperfoil.api.session.Session; class SequenceScopedIntAccess extends SequenceScopedReadAccess implements IntAccess { SequenceScopedIntAccess(Object key, int maxConcurrency) { super(key, maxConcurrency); } @Override public Session.Var createVar(Session session, Session.Var existing) { SessionImpl impl = (SessionImpl) session; if (existing == null) { existing = new ObjectVar(impl); } else if (!(existing instanceof ObjectVar)) { throw new BenchmarkDefinitionException( "Variable " + key + " should hold an object but it is defined to hold an integer elsewhere."); } Object contents = existing.objectValue(session); if (contents == null) { ((ObjectVar) existing).set(IntVar.newArray(session, maxConcurrency)); } else if (contents instanceof IntVar[]) { IntVar[] oldArray = (IntVar[]) contents; if (oldArray.length < maxConcurrency) { IntVar[] newArray = Arrays.copyOf(oldArray, maxConcurrency); for (int i = oldArray.length; i < newArray.length; ++i) { newArray[i] = new IntVar(impl); } ((ObjectVar) existing).set(newArray); } } else { throw new BenchmarkDefinitionException( "Unexpected content in " + key + ": should hold array of IntVar but holds " + contents); } return existing; } @Override public void setInt(Session session, int value) { ObjectVar var = getVarToSet(session); Object o = getItemFromVar(session, var); if (o instanceof IntVar) { if (trace) { log.trace("#{} {}[{}] <- {}", session.uniqueId(), key, session.currentSequence().index(), value); } ((IntVar) o).set(value); } else { int index = session.currentSequence().index(); throw new IllegalStateException("Variable " + key + "[" + index + "] should contain IntVar but contains " + o); } } @Override public int addToInt(Session session, int delta) { Object o = getItem(session); if (o instanceof IntVar) { IntVar iv = (IntVar) o; if (!iv.isSet()) { int index = session.currentSequence().index(); throw new IllegalStateException("Variable " + key + "[" + index + "] was not set yet!"); } int prev = iv.intValue(session); if (trace) { log.trace("#{} {}[{}] += {}", session.uniqueId(), key, session.currentSequence().index(), delta); } iv.add(delta); return prev; } else { int index = session.currentSequence().index(); throw new IllegalStateException("Variable " + key + "[" + index + "] should contain IntVar but contains " + o); } } @Override public void unset(Session session) { ObjectVar var = getVarToSet(session); Object o = getItemFromVar(session, var); if (o instanceof IntVar) { if (trace) { log.trace("#{} unset {}[{}]", session.uniqueId(), key, session.currentSequence().index()); } ((IntVar) o).unset(); } else { int index = session.currentSequence().index(); throw new IllegalStateException( "Variable " + key + "[" + index + "] should contain Session.Var(Object) but contains " + o); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/GlobalDataImpl.java
core/src/main/java/io/hyperfoil/core/session/GlobalDataImpl.java
package io.hyperfoil.core.session; import java.util.AbstractQueue; import java.util.ArrayDeque; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Queue; import java.util.stream.Collectors; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.session.GlobalData; import io.netty.channel.EventLoop; public class GlobalDataImpl implements GlobalData { private static final Logger log = LogManager.getLogger(GlobalDataImpl.class); private static final PoisonedQueue POISON = new PoisonedQueue(); private final EventLoop executor; private final Map<String, String> publishingPhase = new HashMap<>(); private final Map<String, GlobalData.Element> published = new HashMap<>(); private final Map<String, Queue<GlobalData.Element>> toPublish = new HashMap<>(); public GlobalDataImpl(EventLoop executor) { this.executor = executor; } @Override public void publish(String phase, String key, Element element) { assert executor.inEventLoop(); String otherPhase = publishingPhase.put(key, phase); if (otherPhase != null && !otherPhase.equals(phase)) { throw new IllegalStateException( "Global record for key '" + key + "' is published by phase '" + phase + "', no other phase can publish it."); } Queue<Element> queue = toPublish.computeIfAbsent(key, k -> new ArrayDeque<>()); if (queue == POISON) { throw new IllegalStateException( "Global record for key '" + key + "' has already been published; cannot add any more records."); } queue.add(element); } @Override public Element read(String key) { assert executor.inEventLoop(); Element element = published.get(key); if (element == null) { throw new IllegalStateException("Cannot retrieve global record for key '" + key + "' - probably it was not published yet. Make sure the publishing phase and this phase are strictly ordered."); } return element; } public GlobalData.Element extractOne(String key) { Queue<Element> queue = toPublish.get(key); if (queue == null || queue.isEmpty()) { return null; } Element first = queue.remove(); if (queue.isEmpty()) { return first; } Accumulator accumulator = first.newAccumulator(); accumulator.add(first); Element next; while ((next = queue.poll()) != null) { accumulator.add(next); } toPublish.put(key, POISON); return accumulator.complete(); } public void add(Map<String, Element> data) { assert executor.inEventLoop(); for (var entry : data.entrySet()) { GlobalData.Element prev = published.put(entry.getKey(), entry.getValue()); if (prev != null) { log.error("Global data for key {} has been overridden: previous: {}, new: {}", entry.getKey(), prev, entry.getValue()); assert false; } } } public static class Collector { private final Map<String, GlobalData.Accumulator> accumulators = new HashMap<>(); public void collect(String phase, GlobalDataImpl data) { assert data.executor.inEventLoop(); for (var entry : data.publishingPhase.entrySet()) { if (!phase.equals(entry.getValue())) { continue; } Element reduced = data.extractOne(entry.getKey()); synchronized (this) { GlobalData.Accumulator accumulator = accumulators.get(entry.getKey()); if (accumulator == null) { accumulator = reduced.newAccumulator(); accumulators.put(entry.getKey(), accumulator); } accumulator.add(reduced); } } } public synchronized Map<String, GlobalData.Element> extract() { Map<String, Element> newData = accumulators.entrySet().stream() .collect(Collectors.toMap(Map.Entry::getKey, entry -> entry.getValue().complete())); accumulators.clear(); return newData; } } private static class PoisonedQueue extends AbstractQueue<Element> { @Override public Iterator<Element> iterator() { throw new UnsupportedOperationException(); } @Override public int size() { return 0; } @Override public boolean offer(Element element) { throw new UnsupportedOperationException(); } @Override public Element poll() { throw new UnsupportedOperationException(); } @Override public Element peek() { throw new UnsupportedOperationException(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/SimpleReadAccess.java
core/src/main/java/io/hyperfoil/core/session/SimpleReadAccess.java
package io.hyperfoil.core.session; import io.hyperfoil.api.session.Session; public class SimpleReadAccess extends BaseAccess { public SimpleReadAccess(Object key) { super(key); } @Override public boolean isSet(Session session) { SessionImpl impl = (SessionImpl) session; return impl.getVar(index).isSet(); } @Override public Object getObject(Session session) { SessionImpl impl = (SessionImpl) session; return impl.requireSet(index, key).objectValue(session); } @Override public int getInt(Session session) { SessionImpl impl = (SessionImpl) session; IntVar var = impl.requireSet(index, key); return var.intValue(impl); } @Override public Session.Var getVar(Session session) { SessionImpl impl = (SessionImpl) session; return impl.getVar(index); } @Override public boolean isSequenceScoped() { return false; } @Override public String toString() { return key.toString(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/SpecialAccess.java
core/src/main/java/io/hyperfoil/core/session/SpecialAccess.java
package io.hyperfoil.core.session; import java.io.Serializable; import java.util.Objects; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.function.SerializableFunction; import io.hyperfoil.function.SerializableToIntFunction; abstract class SpecialAccess implements ReadAccess { final String name; SpecialAccess(String name) { this.name = Objects.requireNonNull(name); } @Override public boolean isSequenceScoped() { return false; } @Override public java.lang.Object key() { // we return null instead of `name` to avoid the read-without-write check return null; } @Override public void setIndex(int index) { throw new UnsupportedOperationException(); } @Override public int index() { throw new UnsupportedOperationException(); } @Override public boolean isSet(Session session) { return true; } @Override public boolean equals(java.lang.Object obj) { if (obj instanceof ReadAccess) { return name.equals(((ReadAccess) obj).key()); } else { return false; } } @Override public int hashCode() { return Objects.hash(name); } private abstract class BaseVar implements Session.Var, Serializable { @Override public boolean isSet() { return true; } @Override public void unset() { throw new UnsupportedOperationException("Cannot unset " + name + "; it is read-only."); } @Override public String toString() { return "(special:" + name + ")"; } } static class Int extends SpecialAccess { private final SerializableToIntFunction<Session> supplier; private final Var var = new Var(); Int(String name, SerializableToIntFunction<Session> supplier) { super(name); this.supplier = supplier; } @Override public Object getObject(Session session) { throw new UnsupportedOperationException("Cannot retrieve " + name + " as object"); } @Override public int getInt(Session session) { return supplier.applyAsInt(session); } @Override public Session.Var getVar(Session session) { return var; } private class Var extends BaseVar { @Override public Session.VarType type() { return Session.VarType.INTEGER; } @Override public int intValue(Session session) { return supplier.applyAsInt(session); } } } static class Object extends SpecialAccess { private final SerializableFunction<Session, java.lang.Object> supplier; private final Var var = new Var(); Object(String name, SerializableFunction<Session, java.lang.Object> supplier) { super(name); this.supplier = supplier; } @Override public boolean isSet(Session session) { return true; } @Override public java.lang.Object getObject(Session session) { return supplier.apply(session); } @Override public int getInt(Session session) { throw new UnsupportedOperationException("Cannot retrieve " + name + " as integer"); } @Override public Session.Var getVar(Session session) { return var; } private class Var extends BaseVar { @Override public Session.VarType type() { return Session.VarType.OBJECT; } public java.lang.Object objectValue(Session session) { return supplier.apply(session); } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/SequenceScopedObjectAccess.java
core/src/main/java/io/hyperfoil/core/session/SequenceScopedObjectAccess.java
package io.hyperfoil.core.session; import java.util.Arrays; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.Session; class SequenceScopedObjectAccess extends SequenceScopedReadAccess implements ObjectAccess { SequenceScopedObjectAccess(Object key, int maxConcurrency) { super(key, maxConcurrency); } @Override public Session.Var createVar(Session session, Session.Var existing) { // When a step/action sets a variable, it doesn't know if that's a global or sequence-scoped // and must declare it, just in case. SessionImpl impl = (SessionImpl) session; if (existing == null) { existing = new ObjectVar(impl); } if (!(existing instanceof ObjectVar)) { throw new BenchmarkDefinitionException( "Variable " + key + " should hold an object but it is defined to hold an integer elsewhere."); } Object contents = existing.objectValue(session); if (contents == null) { ((ObjectVar) existing).set(ObjectVar.newArray(session, maxConcurrency)); } else if (contents instanceof ObjectVar[]) { ObjectVar[] oldArray = (ObjectVar[]) contents; if (oldArray.length < maxConcurrency) { ObjectVar[] newArray = Arrays.copyOf(oldArray, maxConcurrency); for (int i = oldArray.length; i < newArray.length; ++i) { newArray[i] = new ObjectVar(impl); } ((ObjectVar) existing).set(newArray); } } else { throw new BenchmarkDefinitionException( "Unexpected content in " + key + ": should hold array of ObjectVar but holds " + contents); } return existing; } @Override public void setObject(Session session, Object value) { ObjectVar var = getVarToSet(session); Object o = getItemFromVar(session, var); if (o instanceof ObjectVar) { if (trace) { log.trace("#{} {}[{}] <- {}", session.uniqueId(), key, session.currentSequence().index(), value); } ((ObjectVar) o).set(value); } else { int index = session.currentSequence().index(); throw new IllegalStateException("Variable " + key + "[" + index + "] should contain ObjectVar but contains " + o); } } @Override public Object activate(Session session) { Object o = getItem(session); if (o instanceof ObjectVar) { ObjectVar ov = (ObjectVar) o; if (trace) { log.trace("#{} activate {}[{}]", session.uniqueId(), key, session.currentSequence().index()); } ov.set = true; return ov.objectValue(session); } else { int index = session.currentSequence().index(); throw new IllegalStateException("Variable " + key + "[" + index + "] should contain ObjectVar but contains " + o); } } @Override public void unset(Session session) { ObjectVar var = getVarToSet(session); Object o = getItemFromVar(session, var); if (o instanceof ObjectVar) { if (trace) { log.trace("#{} unset {}[{}]", session.uniqueId(), key, session.currentSequence().index()); } ((ObjectVar) o).unset(); } else { int index = session.currentSequence().index(); throw new IllegalStateException( "Variable " + key + "[" + index + "] should contain Session.Var(Object) but contains " + o); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/SessionImpl.java
core/src/main/java/io/hyperfoil/core/session/SessionImpl.java
package io.hyperfoil.core.session; import java.util.ArrayList; import java.util.BitSet; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.function.Supplier; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.FormattedMessage; import io.hyperfoil.api.collection.LimitedPool; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.config.Scenario; import io.hyperfoil.api.config.Sequence; import io.hyperfoil.api.connection.Request; import io.hyperfoil.api.session.AgentData; import io.hyperfoil.api.session.GlobalData; import io.hyperfoil.api.session.PhaseInstance; import io.hyperfoil.api.session.SequenceInstance; import io.hyperfoil.api.session.Session; import io.hyperfoil.api.session.SessionStopException; import io.hyperfoil.api.session.ThreadData; import io.hyperfoil.api.statistics.SessionStatistics; import io.hyperfoil.api.statistics.Statistics; import io.netty.util.concurrent.EventExecutor; class SessionImpl implements Session { private static final Logger log = LogManager.getLogger(SessionImpl.class); private static final boolean trace = log.isTraceEnabled(); private final Var[] vars; private final Map<ResourceKey<?>, Object> resources = new HashMap<>(); private final List<Var> allVars = new ArrayList<>(); private final List<Resource> allResources = new ArrayList<>(); private final LimitedPool<SequenceInstance> sequencePool; private final SequenceInstance[] runningSequences; private final BitSet usedSequences; private final Consumer<SequenceInstance> releaseSequence = this::releaseSequence; private PhaseInstance phase; private int lastRunningSequence = -1; private SequenceInstance currentSequence; private Request currentRequest; private boolean scheduled; private boolean resetting = true; private EventExecutor executor; private ThreadData threadData; private AgentData agentData; private GlobalData globalData; private SessionStatistics statistics; private final int threadId; private final int uniqueId; private final Runnable deferredStart = this::deferredStart; private final Runnable runTask = this::run; SessionImpl(Scenario scenario, int threadId, int uniqueId) { this.sequencePool = new LimitedPool<>(scenario.maxSequences(), SequenceInstance::new); this.threadId = threadId; this.runningSequences = new SequenceInstance[scenario.maxSequences()]; this.usedSequences = new BitSet(scenario.sumConcurrency()); this.uniqueId = uniqueId; this.vars = scenario.createVars(this); } @Override public void reserve(Scenario scenario) { Sequence[] sequences = scenario.sequences(); for (int i = 0; i < sequences.length; i++) { // We set current sequence so that we know the concurrency of current context in declareResource() Sequence sequence = sequences[i]; currentSequence(sequencePool.acquire().reset(sequence, 0, null, null)); sequence.reserve(this); sequencePool.release(currentSequence); currentSequence = null; } } @Override public Runnable runTask() { return runTask; } @Override public int uniqueId() { return uniqueId; } @Override public int agentThreadId() { return threadId; } @Override public int agentThreads() { return phase.agentThreads(); } @Override public int globalThreadId() { return phase.agentFirstThreadId() + threadId; } @Override public int globalThreads() { Benchmark benchmark = phase.definition().benchmark(); return benchmark.totalThreads(); } @Override public int agentId() { return phase.agentId(); } @Override public int agents() { return phase.definition().benchmark().agents().length; } @Override public String runId() { return phase.runId(); } @Override public EventExecutor executor() { return executor; } @Override public ThreadData threadData() { return threadData; } @Override public AgentData agentData() { return agentData; } @Override public GlobalData globalData() { return globalData; } @Override public PhaseInstance phase() { return phase; } @Override public long phaseStartTimestamp() { return phase.absoluteStartTime(); } void registerVar(Var var) { allVars.add(var); } @Override public <R extends Resource> void declareResource(ResourceKey<R> key, Supplier<R> resourceSupplier) { declareResource(key, resourceSupplier, false); } @Override public <R extends Resource> void declareResource(ResourceKey<R> key, Supplier<R> resourceSupplier, boolean singleton) { if (resources.containsKey(key)) { return; } // Current sequence should be null only during unit testing int concurrency = currentSequence == null ? 0 : currentSequence.definition().concurrency(); if (!singleton && concurrency > 0) { Resource[] array = new Resource[concurrency]; for (int i = 0; i < concurrency; ++i) { R resource = resourceSupplier.get(); array[i] = resource; allResources.add(resource); } resources.put(key, array); } else { R resource = resourceSupplier.get(); resources.put(key, resource); allResources.add(resource); } } @Override public <R extends Resource> void declareSingletonResource(ResourceKey<R> key, R resource) { if (resources.containsKey(key)) { return; } resources.put(key, resource); allResources.add(resource); } @SuppressWarnings("unchecked") @Override public <R extends Resource> R getResource(ResourceKey<R> key) { Object res = resources.get(key); if (res == null) { return null; } else if (res.getClass().isArray() && res instanceof Resource[]) { Resource[] array = (Resource[]) res; return (R) array[currentSequence.index()]; } else { return (R) res; } } @SuppressWarnings("unchecked") <V extends Var> V getVar(int index) { return (V) vars[index]; } @SuppressWarnings("unchecked") <V extends Var> V requireSet(int index, Object key) { Var var = vars[index]; if (!var.isSet()) { throw new IllegalStateException("Variable " + key + " was not set yet!"); } return (V) var; } private void run() { scheduled = false; try { runSession(); } catch (SessionStopException e) { log.trace("#{} Session was stopped.", uniqueId); // this one is OK } catch (Throwable t) { log.error(new FormattedMessage("#{} Uncaught error", uniqueId), t); if (phase != null) { phase.fail(t); } } } public void runSession() { if (phase.status() == PhaseInstance.Status.TERMINATED) { if (trace) { log.trace("#{} Phase is terminated", uniqueId); } return; } if (lastRunningSequence < 0) { if (trace) { log.trace("#{} No sequences to run, ignoring.", uniqueId); } return; } if (trace) { log.trace("#{} Run ({} running sequences)", uniqueId, lastRunningSequence + 1); } int lastProgressedSequence = -1; while (lastRunningSequence >= 0) { boolean progressed = false; for (int i = 0; i <= lastRunningSequence; ++i) { if (phase.status() == PhaseInstance.Status.TERMINATING) { if (trace) { log.trace("#{} Phase {} is terminating", uniqueId, phase.definition().name()); } stop(); return; } else if (lastProgressedSequence == i) { break; } SequenceInstance sequence = runningSequences[i]; if (sequence == null) { // This may happen when the session.stop() is called continue; } if (sequence.progress(this)) { progressed = true; lastProgressedSequence = i; if (sequence.isCompleted()) { if (trace) { log.trace("#{} Completed {}({})", uniqueId, sequence, sequence.index()); } if (lastRunningSequence == -1) { log.trace("#{} was stopped.", uniqueId); return; } sequence.decRefCnt(this); if (i >= lastRunningSequence) { runningSequences[i] = null; } else { runningSequences[i] = runningSequences[lastRunningSequence]; runningSequences[lastRunningSequence] = null; } --lastRunningSequence; lastProgressedSequence = -1; } } } if (!progressed && lastRunningSequence >= 0) { if (trace) { log.trace("#{} ({}) no progress, not finished.", uniqueId, phase.definition().name()); } return; } } if (trace) { log.trace("#{} Session finished", uniqueId); } if (!resetting) { reset(); phase.notifyFinished(this); } } private void releaseSequence(SequenceInstance sequence) { usedSequences.clear(sequence.definition().offset() + sequence.index()); sequencePool.release(sequence); } @Override public void currentSequence(SequenceInstance current) { if (trace) { log.trace("#{} Changing sequence {} -> {}", uniqueId, currentSequence, current); } currentSequence = current; } public SequenceInstance currentSequence() { return currentSequence; } @Override public void attach(EventExecutor executor, ThreadData threadData, AgentData agentData, GlobalData globalData, SessionStatistics statistics) { assert this.executor == null; this.executor = executor; this.threadData = threadData; this.agentData = agentData; this.globalData = globalData; this.statistics = statistics; } @Override public void start(PhaseInstance phase) { if (trace) { log.trace("#{} Session starting in {}", uniqueId, phase.definition().name); } resetPhase(phase); executor.execute(deferredStart); } private Void deferredStart() { resetting = false; for (Sequence sequence : phase.definition().scenario().initialSequences()) { startSequence(sequence, false, ConcurrencyPolicy.FAIL); } run(); return null; } @Override public SequenceInstance startSequence(String name, boolean forceSameIndex, ConcurrencyPolicy policy) { return startSequence(phase.definition().scenario().sequence(name), forceSameIndex, policy); } private SequenceInstance startSequence(Sequence sequence, boolean forceSameIndex, ConcurrencyPolicy policy) { int index = 0; if (forceSameIndex) { if (currentSequence == null) { fail(new IllegalStateException("Current sequence is not set!")); } else if (sequence.concurrency() != currentSequence.definition().concurrency()) { fail(new IllegalArgumentException("Sequence '" + sequence.name() + "' does not have the same concurrency factor (" + sequence.concurrency() + ") as the spawning sequence '" + currentSequence.definition().name() + "' (" + currentSequence.definition().concurrency() + ")")); } index = currentSequence.index(); } SequenceInstance instance = sequencePool.acquire(); // Lookup first unused index for (;;) { if (sequence.concurrency() == 0) { if (index >= 1) { log.error("Cannot start sequence {} as it has already started and it is not marked as concurrent", sequence.name()); if (sequence == currentSequence.definition()) { log.info("Hint: maybe you intended only to restart the current sequence?"); } sequencePool.release(instance); fail(new IllegalStateException("Cannot start sequence '" + sequence.name() + "' as it is not concurrent")); } } else if (index >= sequence.concurrency()) { if (instance != null) { sequencePool.release(instance); } if (policy == ConcurrencyPolicy.WARN) { log.warn("Cannot start sequence {}, exceeded maximum concurrency ({})", sequence.name(), sequence.concurrency()); } else { log.error("Cannot start sequence {}, exceeded maximum concurrency ({})", sequence.name(), sequence.concurrency()); fail(new IllegalStateException("Concurrency limit exceeded")); } return null; } if (!usedSequences.get(sequence.offset() + index)) { break; } else if (forceSameIndex) { if (policy == ConcurrencyPolicy.WARN) { log.warn("Cannot start sequence {} with index {} as it is already executing.", sequence.name(), index); } else { log.error("Cannot start sequence {} with index {} as it is already executing.", sequence.name(), index); fail(new IllegalArgumentException("Cannot start sequence with forced index.")); } } ++index; } if (instance == null) { log.error("Cannot instantiate sequence {}, no free instances.", sequence.name()); fail(new IllegalStateException("No free sequence instances")); } else { log.trace("#{} starting sequence {}({})", uniqueId(), sequence.name(), index); usedSequences.set(sequence.offset() + index); instance.reset(sequence, index, sequence.steps(), releaseSequence); if (lastRunningSequence >= runningSequences.length - 1) { throw new IllegalStateException("Maximum number of scheduled sequences exceeded!"); } lastRunningSequence++; assert runningSequences[lastRunningSequence] == null; runningSequences[lastRunningSequence] = instance; } return instance; } @Override public void proceed() { if (!scheduled) { scheduled = true; executor.execute(runTask); } } @Override public Statistics statistics(int stepId, String name) { return statistics.getOrCreate(phase.definition(), stepId, name, phase.absoluteStartTime()); } @Override public void pruneStats(Phase phase) { statistics.prune(phase); } @Override public void reset() { resetting = true; for (int i = 0; i < allVars.size(); ++i) { allVars.get(i).unset(); } for (int i = 0; i < allResources.size(); i++) { Resource r = allResources.get(i); r.onSessionReset(this); } assert usedSequences.isEmpty(); assert sequencePool.isFull(); } public void resetPhase(PhaseInstance newPhase) { // I dislike having non-final phase but it helps not reallocating the resources... if (phase == newPhase) { return; } assert phase == null || newPhase.definition().scenario() == phase.definition().scenario(); assert phase == null || newPhase.definition().sharedResources.equals(phase.definition().sharedResources); assert phase == null || phase.status().isTerminated(); phase = newPhase; } @Override public void stop() { for (int i = 0; i <= lastRunningSequence; ++i) { SequenceInstance sequence = runningSequences[i]; sequence.decRefCnt(this); runningSequences[i] = null; } lastRunningSequence = -1; currentSequence = null; if (trace) { log.trace("#{} Session stopped.", uniqueId); } if (!resetting) { reset(); phase.notifyFinished(this); } throw SessionStopException.INSTANCE; } @Override public void fail(Throwable t) { log.error(new FormattedMessage("#{} Failing phase {}", uniqueId, phase.definition().name), t); // we need to fail the phase before stopping as stop() could cause termination // without recording the error on its own. phase.fail(t); stop(); } @Override public boolean isActive() { return lastRunningSequence >= 0; } @Override public Request currentRequest() { return currentRequest; } @Override public void currentRequest(Request request) { this.currentRequest = request; } @Override public String toString() { StringBuilder sb = new StringBuilder("#").append(uniqueId) .append(" (").append(phase != null ? phase.definition().name : null).append(") ") .append(lastRunningSequence + 1).append(" sequences:"); for (int i = 0; i <= lastRunningSequence; ++i) { sb.append(' '); runningSequences[i].appendTo(sb); } return sb.toString(); } public void destroy() { for (var resource : allResources) { resource.destroy(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/SimpleIntAccess.java
core/src/main/java/io/hyperfoil/core/session/SimpleIntAccess.java
package io.hyperfoil.core.session; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.session.IntAccess; import io.hyperfoil.api.session.Session; public class SimpleIntAccess extends SimpleReadAccess implements IntAccess { public SimpleIntAccess(Object key) { super(key); } @Override public Session.Var createVar(Session session, Session.Var existing) { if (existing == null) { return new IntVar((SessionImpl) session); } else if (existing instanceof IntVar) { return existing; } else { throw new BenchmarkDefinitionException( "Variable " + key + " should hold an integer but it is defined to hold an object elsewhere."); } } @Override public void setInt(Session session, int value) { SessionImpl impl = (SessionImpl) session; if (trace) { log.trace("#{} {} <- {}", impl.uniqueId(), key, value); } impl.<IntVar> getVar(index).set(value); } @Override public int addToInt(Session session, int delta) { SessionImpl impl = (SessionImpl) session; IntVar var = impl.requireSet(index, key); int prev = var.intValue(session); if (trace) { log.trace("#{} {} <- {}", impl.uniqueId(), key, prev + delta); } var.set(prev + delta); return prev; } @Override public void unset(Session session) { SessionImpl impl = (SessionImpl) session; impl.getVar(index).unset(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/BaseAccess.java
core/src/main/java/io/hyperfoil/core/session/BaseAccess.java
package io.hyperfoil.core.session; import java.util.Objects; import io.hyperfoil.api.session.ReadAccess; public abstract class BaseAccess implements ReadAccess { protected final Object key; protected int index = -1; public BaseAccess(Object key) { this.key = Objects.requireNonNull(key); } @Override public Object key() { return key; } @Override public void setIndex(int index) { assert this.index < 0 || this.index == index : "Current index " + this.index + ", suggested index " + index; this.index = index; } @Override public int index() { return index; } @Override public boolean equals(Object obj) { if (obj instanceof ReadAccess) { return key.equals(((ReadAccess) obj).key()); } else { return false; } } @Override public int hashCode() { return Objects.hash(key); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/IntVar.java
core/src/main/java/io/hyperfoil/core/session/IntVar.java
package io.hyperfoil.core.session; import io.hyperfoil.api.session.Session; public class IntVar implements Session.Var { private boolean set; private int value; IntVar(SessionImpl session) { session.registerVar(this); } public static IntVar[] newArray(Session session, int size) { IntVar[] array = new IntVar[size]; for (int i = 0; i < array.length; ++i) array[i] = new IntVar((SessionImpl) session); return array; } @Override public Session.VarType type() { return Session.VarType.INTEGER; } @Override public int intValue(Session session) { return value; } @Override public boolean isSet() { return set; } @Override public void unset() { set = false; } public int get() { assert set; return value; } public void set(int value) { this.value = value; this.set = true; } public void add(int delta) { assert set; this.value += delta; } @Override public String toString() { if (set) { return "(int:" + value + ")"; } else { return "(int:unset)"; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/SessionFactory.java
core/src/main/java/io/hyperfoil/core/session/SessionFactory.java
package io.hyperfoil.core.session; import java.util.Collections; import java.util.function.BiFunction; import java.util.function.Function; import io.hyperfoil.api.config.Benchmark; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Locator; import io.hyperfoil.api.config.Phase; import io.hyperfoil.api.config.Scenario; import io.hyperfoil.api.config.Sequence; import io.hyperfoil.api.config.Step; import io.hyperfoil.api.session.IntAccess; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.api.session.WriteAccess; import io.hyperfoil.core.impl.PhaseInstanceImpl; import io.hyperfoil.core.util.Unique; import io.netty.util.concurrent.EventExecutorGroup; import io.netty.util.concurrent.ImmediateEventExecutor; public final class SessionFactory { private static final SpecialAccess[] SPECIAL = { new SpecialAccess.Int("hyperfoil.agent.id", Session::agentId), new SpecialAccess.Int("hyperfoil.agents", Session::agents), new SpecialAccess.Int("hyperfoil.agent.thread.id", Session::agentThreadId), new SpecialAccess.Int("hyperfoil.agent.threads", Session::agentThreads), new SpecialAccess.Int("hyperfoil.global.thread.id", Session::globalThreadId), new SpecialAccess.Int("hyperfoil.global.threads", Session::globalThreads), new SpecialAccess.Object("hyperfoil.phase.name", s -> s.phase().definition().name), new SpecialAccess.Int("hyperfoil.phase.id", s -> s.phase().definition().id), new SpecialAccess.Int("hyperfoil.phase.iteration", s -> s.phase().definition().iteration), new SpecialAccess.Object("hyperfoil.phase.start.time.as.string", s -> s.phase().absoluteStartTimeAsString()), new SpecialAccess.Object("hyperfoil.run.id", Session::runId), new SpecialAccess.Int("hyperfoil.session.id", Session::uniqueId), }; public static Session create(Scenario scenario, int executorId, int uniqueId) { return new SessionImpl(scenario, executorId, uniqueId); } public static Session forTesting(WriteAccess... accesses) { Scenario dummyScenario = new Scenario(new Sequence[0], new Sequence[] { new Sequence("dummy", 0, 1, 0, new Step[0]) { WriteAccess[] dummyAccesses = accesses; } }, 16, 16); SessionImpl session = new SessionImpl(dummyScenario, 0, 0); Phase dummyPhase = new Phase(Benchmark::forTesting, 0, 0, "dummy", dummyScenario, 0, Collections.emptyList(), Collections.emptyList(), Collections.emptyList(), 0, -1, null, false, () -> "dummy", Collections.emptyMap(), null); session.resetPhase(new PhaseInstanceImpl(dummyPhase, "dummy", 0) { @Override public void proceed(EventExecutorGroup executorGroup) { } @Override public void reserveSessions() { } }); session.attach(ImmediateEventExecutor.INSTANCE, null, null, null, null); session.reserve(dummyScenario); return session; } private SessionFactory() { } public static ReadAccess readAccess(Object key) { if (key instanceof String) { String expression = (String) key; if (expression.startsWith("hyperfoil.")) { for (SpecialAccess access : SPECIAL) { if (access.name.equals(expression)) { return access; } } throw new BenchmarkDefinitionException("No special variable " + expression); } } return access(key, SimpleReadAccess::new, SequenceScopedReadAccess::new); } public static ObjectAccess objectAccess(Object key) { return access(key, SimpleObjectAccess::new, SequenceScopedObjectAccess::new); } public static IntAccess intAccess(Object key) { return access(key, SimpleIntAccess::new, SequenceScopedIntAccess::new); } public static <A extends ReadAccess> A access(Object key, Function<Object, A> simple, BiFunction<Object, Integer, A> sequenceScoped) { // This should be invoked only from prepareBuild() or build() assert Locator.current() != null; if (key == null) { return null; } else if (key instanceof String) { String expression = (String) key; if (expression.endsWith("[.]")) { return sequenceScoped.apply(expression.substring(0, expression.length() - 3), getMaxConcurrency()); } else { return simple.apply(key); } } else if (key instanceof Unique) { if (((Unique) key).isSequenceScoped()) { return sequenceScoped.apply(key, getMaxConcurrency()); } else { return simple.apply(key); } } else { return simple.apply(key); } } public static ReadAccess sequenceScopedReadAccess(Object key) { return sequenceScopedObjectAccess(key); } public static ObjectAccess sequenceScopedObjectAccess(Object key) { return new SequenceScopedObjectAccess(key, getMaxConcurrency()); } public static IntAccess sequenceScopedIntAccess(Object key) { return new SequenceScopedIntAccess(key, getMaxConcurrency()); } private static int getMaxConcurrency() { Locator locator = Locator.current(); assert locator != null; int maxConcurrency = locator.sequence().rootSequence().concurrency(); if (maxConcurrency <= 0) { throw new BenchmarkDefinitionException(locator.step() + " in sequence " + locator.sequence().name() + " uses sequence-scoped access but this sequence is not declared as concurrent."); } return maxConcurrency; } public static void destroy(Session session) { ((SessionImpl) session).destroy(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/session/ThreadDataImpl.java
core/src/main/java/io/hyperfoil/core/session/ThreadDataImpl.java
package io.hyperfoil.core.session; import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Function; import java.util.function.LongBinaryOperator; import io.hyperfoil.api.session.ThreadData; public class ThreadDataImpl implements ThreadData { private final Map<String, SharedMapSet> maps = new HashMap<>(); private final Map<String, SharedCounterImpl> counters = new HashMap<>(); @Override public void reserveMap(String key, Object match, int entries) { SharedMapSet existing = maps.get(key); if (existing != null) { if (match != null) { if (existing instanceof IndexedSharedMapSet) { ((IndexedSharedMapSet) existing).ensureIndex(match).ensureEntries(entries); } else { maps.put(key, new IndexedSharedMapSet(existing, match, entries)); } } else { existing.ensureEntries(entries); } } else { if (match != null) { maps.put(key, new IndexedSharedMapSet(match, entries)); } else { maps.put(key, new SharedMapSet(entries)); } } } @Override public SharedMap newMap(String key) { SharedMapSet set = maps.get(key); return set.newMap(); } @Override public SharedMap pullMap(String key) { return maps.get(key).acquireRandom(); } @Override public SharedMap pullMap(String key, Object match, Object value) { return maps.get(key).acquireRandom(match, value); } @Override public void pushMap(String key, SharedMap sharedMap) { maps.get(key).insert(sharedMap); } @Override public void releaseMap(String key, SharedMap map) { map.clear(); maps.get(key).release(map); } @Override public SharedCounter reserveCounter(String key) { SharedCounterImpl counter = counters.get(key); if (counter == null) { counter = new SharedCounterImpl(); counters.put(key, counter); } return counter; } @Override public SharedCounter getCounter(String key) { return counters.get(key); } private static class SharedMapSet { MapImpl[] unused; int unusedSize; int maxEntries; MapImpl[] maps; int currentSize; SharedMapSet(int entries) { unused = new MapImpl[16]; maps = new MapImpl[16]; maxEntries = entries; } SharedMapSet(SharedMapSet set, int entries) { assert set.currentSize == 0; assert set.unusedSize == 0; unused = set.unused; maps = set.maps; maxEntries = Math.max(set.maxEntries, entries); } void ensureEntries(int entries) { if (entries > maxEntries) { assert unusedSize == 0; maxEntries = entries; } } SharedMap newMap() { if (unusedSize == 0) { return new MapImpl(maxEntries, numIndices()); } else { SharedMap last = unused[--unusedSize]; unused[unusedSize] = null; return last; } } protected int numIndices() { return 0; } private MapImpl acquireLast() { if (currentSize <= 0) { return null; } int pos = --currentSize; MapImpl map = maps[pos]; maps[pos] = null; return map; } public SharedMap acquireRandom(Object matchKey, Object value) { throw new UnsupportedOperationException("Cannot match " + matchKey + ": not indexed"); } public SharedMap acquireRandom() { if (currentSize == 0) { return null; } int pos = ThreadLocalRandom.current().nextInt(currentSize); if (pos == currentSize - 1) { return acquireLast(); } else { SharedMap map = maps[pos]; maps[pos] = acquireLast(); return map; } } public int insert(SharedMap map) { if (currentSize == maps.length) { maps = Arrays.copyOf(maps, maps.length * 2); } int mainIndex = currentSize++; assert maps[mainIndex] == null; maps[mainIndex] = (MapImpl) map; return mainIndex; } public void release(SharedMap map) { if (unusedSize == unused.length) { unused = Arrays.copyOf(unused, unused.length * 2); } unused[unusedSize++] = (MapImpl) map; } } private static class Positions { private int[] array = new int[16]; private int size; int insert(int target) { if (size == array.length) { array = Arrays.copyOf(array, array.length * 2); } int pos = size++; array[pos] = target; return pos; } int moveLastTo(int pos) { assert size != 0; --size; if (size == 0) { return -1; } return array[pos] = array[size]; } } private static class IndexedSharedMapSet extends SharedMapSet { private Positions[] unusedPositions = new Positions[16]; private int unusedPositionsSize = 0; private Map<Object, Positions>[] positions; private Object[] indices; private final Function<Object, Positions> acquirePosition = ignored -> acquirePosition(); @SuppressWarnings("unchecked") IndexedSharedMapSet(Object indexKey, int entries) { super(entries); this.indices = new Object[] { indexKey }; this.positions = new Map[] { new HashMap<>() }; } @SuppressWarnings("unchecked") IndexedSharedMapSet(SharedMapSet set, Object indexKey, int entries) { super(set, entries); this.indices = new Object[] { indexKey }; this.positions = new Map[] { new HashMap<>() }; } @Override protected int numIndices() { return indices.length; } IndexedSharedMapSet ensureIndex(Object index) { for (Object key : indices) { if (key.equals(index)) return this; } indices = Arrays.copyOf(indices, indices.length + 1); positions = Arrays.copyOf(positions, positions.length + 1); indices[indices.length - 1] = index; positions[positions.length - 1] = new HashMap<>(); return this; } @Override public SharedMap acquireRandom() { if (currentSize == 0) { return null; } return acquireAt(ThreadLocalRandom.current().nextInt(currentSize)); } @Override public SharedMap acquireRandom(Object matchKey, Object value) { Positions ps = null; for (int i = 0; i < indices.length; ++i) { if (indices[i].equals(matchKey)) { ps = positions[i].get(value); if (ps == null) { return null; } } } assert ps != null : "No index for " + matchKey; int mainIndex = ps.array[ThreadLocalRandom.current().nextInt(ps.size)]; return acquireAt(mainIndex); } private SharedMap acquireAt(int mainIndex) { MapImpl map = maps[mainIndex]; assert map.indexLocations.length == indices.length; // remove this map from indices for (int i = 0; i < indices.length; ++i) { Object indexKey = indices[i]; Object value2 = map.get(indexKey); if (value2 == null) { continue; } Positions ps2 = this.positions[i].get(value2); int ps2index = map.indexLocations[i]; int mainIndexUpdated = ps2.moveLastTo(ps2index); if (mainIndexUpdated >= 0) { maps[mainIndexUpdated].indexLocations[i] = ps2index; } else { positions[i].remove(value2); releasePositions(ps2); } } --currentSize; if (mainIndex != currentSize) { // relocate last element (updating its indices) MapImpl relocated = maps[mainIndex] = maps[currentSize]; assert relocated != null; for (int i = 0; i < indices.length; ++i) { Object indexKey = indices[i]; Object value3 = relocated.get(indexKey); if (value3 == null) { continue; } Positions ps3 = positions[i].get(value3); ps3.array[relocated.indexLocations[i]] = mainIndex; } } else { maps[mainIndex] = null; } return map; } @Override public int insert(SharedMap map) { MapImpl impl = (MapImpl) map; int mainIndex = super.insert(map); for (int i = 0; i < indices.length; ++i) { Object value = map.get(indices[i]); impl.indexLocations[i] = positions[i].computeIfAbsent(value, acquirePosition).insert(mainIndex); } return mainIndex; } private void releasePositions(Positions ps) { if (unusedPositionsSize == unusedPositions.length) { unusedPositions = Arrays.copyOf(unusedPositions, unusedPositions.length * 2); } unusedPositions[unusedPositionsSize++] = ps; } private Positions acquirePosition() { if (unusedPositionsSize == 0) { return new Positions(); } return unusedPositions[--unusedPositionsSize]; } } private static class MapImpl implements SharedMap { int[] indexLocations; Object[] keys; Object[] values; int size; MapImpl(int capacity, int indices) { indexLocations = indices > 0 ? new int[indices] : null; keys = new Object[capacity]; values = new Object[capacity]; } @Override public void put(Object key, Object value) { int pos = size++; keys[pos] = key; values[pos] = value; } @Override public int size() { return size; } @Override public int capacity() { return keys.length; } @Override public void clear() { for (int i = size - 1; i >= 0; --i) { keys[i] = null; values[i] = null; } size = 0; } @Override public Object get(Object key) { for (int i = 0; i < size; ++i) { if (keys[i].equals(key)) { return values[i]; } } throw new IllegalArgumentException( "Looking for variable '" + key + "' but this is not set; Available: " + Arrays.asList(keys)); } } private static class SharedCounterImpl implements SharedCounter { private long value; @Override public long get() { return value; } @Override public long set(long value) { long prev = this.value; this.value = value; return prev; } @Override public long apply(LongBinaryOperator operator, long value) { this.value = operator.applyAsLong(this.value, value); return this.value; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/MarkRequestInvalidAction.java
core/src/main/java/io/hyperfoil/core/handlers/MarkRequestInvalidAction.java
package io.hyperfoil.core.handlers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.connection.Request; import io.hyperfoil.api.session.Action; import io.hyperfoil.api.session.Session; public class MarkRequestInvalidAction implements Action { private static final Logger log = LogManager.getLogger(MarkRequestInvalidAction.class); @Override public void run(Session session) { Request request = session.currentRequest(); if (request == null) { log.error("#{} No request in progress", session.uniqueId()); } else { log.trace("#{} Marking request as invalid", session.uniqueId()); request.markInvalid(); } } /** * Unconditionally mark currently processed request as invalid. */ @MetaInfServices(Action.Builder.class) @Name("markRequestInvalid") public static class Builder implements Action.Builder { @Override public Action build() { return new MarkRequestInvalidAction(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/SearchValidator.java
core/src/main/java/io/hyperfoil/core/handlers/SearchValidator.java
package io.hyperfoil.core.handlers; import java.nio.charset.StandardCharsets; import java.util.function.IntPredicate; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.Session; import io.netty.buffer.ByteBuf; /** * Simple pattern (no regexp) search based on Rabin-Karp algorithm. * Does not handle the intricacies of UTF-8 mapping same strings to different bytes. */ public class SearchValidator implements Processor, ResourceUtilizer, Session.ResourceKey<SearchValidator.Context> { private final byte[] text; private final int hash; private final int coef; private final IntPredicate match; /** * @param text Search pattern. * @param match Expected number of matches. */ public SearchValidator(String text, IntPredicate match) { this.text = text.getBytes(StandardCharsets.UTF_8); this.match = match; this.hash = BaseSearchContext.computeHash(this.text); this.coef = BaseSearchContext.computeCoef(this.text.length); } @Override public void process(Session session, ByteBuf data, final int offset, int length, boolean isLastPart) { Context ctx = session.getResource(this); ctx.add(data, offset, length); int endIndex = offset + length; int index = ctx.initHash(offset, text.length); index = test(ctx, index); while (index < endIndex) { ctx.advance(data.getByte(index++), coef, index, text.length + 1); index = test(ctx, index); } } private int test(Context ctx, int index) { if (ctx.currentHash == hash) { for (int i = 0; i < text.length; ++i) { if (text[i] != ctx.byteRelative(index, text.length - i)) { return i; } } ctx.matches++; ctx.currentHash = 0; ctx.hashedBytes = 0; return ctx.initHash(index, text.length); } return index; } @Override public void before(Session session) { Context ctx = session.getResource(this); ctx.reset(); } @Override public void after(Session session) { Context ctx = session.getResource(this); boolean match = this.match.test(ctx.matches); ctx.reset(); if (!match) { session.currentRequest().markInvalid(); } } @Override public void reserve(Session session) { session.declareResource(this, Context::new); } static class Context extends BaseSearchContext { int matches; @Override public void reset() { super.reset(); matches = 0; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/SearchHandler.java
core/src/main/java/io/hyperfoil/core/handlers/SearchHandler.java
package io.hyperfoil.core.handlers; import java.nio.charset.StandardCharsets; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.Session; import io.netty.buffer.ByteBuf; /** * Simple pattern (no regexp) search based on Rabin-Karp algorithm. * Does not handle the intricacies of UTF-8 mapping same strings to different bytes. */ public class SearchHandler implements Processor, ResourceUtilizer, Session.ResourceKey<SearchHandler.Context> { private final byte[] begin, end; private final int beginHash, endHash; private final int beginCoef, endCoef; private Processor processor; public SearchHandler(String begin, String end, Processor processor) { this.begin = begin.getBytes(StandardCharsets.UTF_8); this.end = end.getBytes(StandardCharsets.UTF_8); this.beginHash = BaseSearchContext.computeHash(this.begin); this.beginCoef = BaseSearchContext.computeCoef(this.begin.length); this.endHash = BaseSearchContext.computeHash(this.end); this.endCoef = BaseSearchContext.computeCoef(this.end.length); this.processor = processor; } @Override public void before(Session session) { Context ctx = session.getResource(this); ctx.reset(); processor.before(session); } @Override public void process(Session session, ByteBuf data, final int offset, int length, boolean isLast) { Context ctx = session.getResource(this); ctx.add(data, offset, length); int endIndex = offset + length; int index = ctx.initHash(offset, ctx.lookupText.length); while (ctx.test(index)) { if (ctx.lookupText == end) { fireProcessor(ctx, session, index); } else { ctx.mark(index); } ctx.swap(); index = ctx.initHash(index, ctx.lookupText.length); } while (index < endIndex) { ctx.advance(data.getByte(index++), ctx.lookupCoef, index, ctx.lookupText.length + 1); while (ctx.test(index)) { if (ctx.lookupText == end) { fireProcessor(ctx, session, index); } else { ctx.mark(index); } ctx.swap(); index = ctx.initHash(index, ctx.lookupText.length); } } } private void fireProcessor(Context ctx, Session session, int index) { int endPart = ctx.currentPart; int endPos = index - end.length; while (endPos < 0) { endPart--; if (endPart < 0) { endPart = 0; endPos = 0; } else { endPos += ctx.endIndices[endPart]; } } while (ctx.markPart < endPart) { ByteBuf data = ctx.parts[ctx.markPart]; // if the begin ends with part, we'll skip the 0-length process call int length = ctx.endIndices[ctx.markPart] - ctx.markPos; if (length > 0) { processor.process(session, data, ctx.markPos, length, false); } ctx.markPos = 0; ctx.markPart++; } processor.process(session, ctx.parts[endPart], ctx.markPos, endPos - ctx.markPos, true); } @Override public void after(Session session) { Context ctx = session.getResource(this); // release buffers ctx.reset(); processor.after(session); } @Override public void reserve(Session session) { session.declareResource(this, Context::new); } class Context extends BaseSearchContext { byte[] lookupText; int lookupHash; int lookupCoef; int markPart = -1; int markPos = -1; void swap() { currentHash = 0; hashedBytes = 0; if (lookupText == end) { lookupText = begin; lookupHash = beginHash; lookupCoef = beginCoef; } else { lookupText = end; lookupHash = endHash; lookupCoef = endCoef; } } boolean test(int index) { if (currentHash == lookupHash) { for (int i = 0; i < lookupText.length; ++i) { if (lookupText[i] != byteRelative(index, lookupText.length - i)) { return false; } } return true; } return false; } @Override void shiftParts() { super.shiftParts(); --markPart; if (markPart < 0) { markPart = 0; markPos = 0; } } @Override void reset() { super.reset(); lookupText = begin; lookupHash = beginHash; lookupCoef = beginCoef; markPart = -1; markPos = -1; } void mark(int index) { markPart = currentPart; markPos = index; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/DebugProcessor.java
core/src/main/java/io/hyperfoil/core/handlers/DebugProcessor.java
package io.hyperfoil.core.handlers; import java.nio.charset.StandardCharsets; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.Session; import io.netty.buffer.ByteBuf; public class DebugProcessor implements Processor { private static final Logger log = LogManager.getLogger(DebugProcessor.class); @Override public void before(Session session) { log.debug("Before"); } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { log.debug("Process (last? {}): '{}'", isLastPart, data.toString(offset, length, StandardCharsets.UTF_8)); } @Override public void after(Session session) { log.debug("After"); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/TransferSizeRecorder.java
core/src/main/java/io/hyperfoil/core/handlers/TransferSizeRecorder.java
package io.hyperfoil.core.handlers; import org.kohsuke.MetaInfServices; import com.fasterxml.jackson.annotation.JsonTypeName; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.connection.Request; import io.hyperfoil.api.processor.RawBytesHandler; import io.hyperfoil.api.statistics.Statistics; import io.hyperfoil.api.statistics.StatsExtension; import io.netty.buffer.ByteBuf; public class TransferSizeRecorder implements RawBytesHandler { private final String key; public TransferSizeRecorder(String key) { this.key = key; } @Override public void onRequest(Request request, ByteBuf buf, int offset, int length) { Statistics statistics = request.statistics(); statistics.update(key, request.startTimestampMillis(), Stats::new, (s, l) -> s.sent += l, length); } @Override public void onResponse(Request request, ByteBuf buf, int offset, int length, boolean isLastPart) { Statistics statistics = request.statistics(); statistics.update(key, request.startTimestampMillis(), Stats::new, (s, l) -> s.received += l, length); } /** * Accumulates request and response sizes into custom metrics. */ @MetaInfServices(RawBytesHandler.Builder.class) @Name("transferSizeRecorder") public static class Builder implements RawBytesHandler.Builder { private String key; /** * Name of the custom metric for collecting request/response bytes. * * @param metric Name of the custom metric. * @return Self. */ public Builder key(String metric) { this.key = metric; return this; } @Override public TransferSizeRecorder build() { return new TransferSizeRecorder(key); } } @MetaInfServices(StatsExtension.class) @JsonTypeName("transfersize") public static class Stats implements StatsExtension { private static final String[] HEADERS = { "sent", "received" }; public long sent; public long received; @Override public boolean isNull() { return sent + received == 0; } @Override public void add(StatsExtension other) { if (other instanceof Stats) { Stats o = (Stats) other; sent += o.sent; received += o.received; } else { throw new IllegalArgumentException(other.toString()); } } @Override public void subtract(StatsExtension other) { if (other instanceof Stats) { Stats o = (Stats) other; sent -= o.sent; received -= o.received; } else { throw new IllegalArgumentException(other.toString()); } } @Override public void reset() { sent = 0; received = 0; } @Override public StatsExtension clone() { Stats copy = new Stats(); copy.sent = sent; copy.received = received; return copy; } @Override public String[] headers() { return HEADERS; } @Override public String byHeader(String header) { switch (header) { case "sent": return String.valueOf(sent); case "received": return String.valueOf(received); default: return "<unknown header: " + header + ">"; } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/ConditionalAction.java
core/src/main/java/io/hyperfoil/core/handlers/ConditionalAction.java
package io.hyperfoil.core.handlers; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Embed; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.session.Action; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.Condition; public class ConditionalAction extends BaseDelegatingAction { private final Condition condition; public ConditionalAction(Condition condition, Action[] actions) { super(actions); this.condition = condition; } @Override public void run(Session session) { if (condition.test(session)) { super.run(session); } } /** * Perform an action or sequence of actions conditionally. */ @MetaInfServices(Action.Builder.class) @Name("conditional") public static class Builder extends BaseDelegatingAction.Builder<Builder> { private Condition.TypesBuilder<Builder> condition = new Condition.TypesBuilder<>(this); @Embed public Condition.TypesBuilder<Builder> condition() { return condition; } @Override public Action build() { Condition condition = this.condition.buildCondition(); if (condition == null) { throw new BenchmarkDefinitionException("Conditional action requires a condition."); } return new ConditionalAction(condition, buildActions()); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/QueueProcessor.java
core/src/main/java/io/hyperfoil/core/handlers/QueueProcessor.java
package io.hyperfoil.core.handlers; import java.util.concurrent.ThreadLocalRandom; import java.util.function.Consumer; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Locator; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.config.SequenceBuilder; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.Action; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.ServiceLoadedBuilderProvider; import io.hyperfoil.core.data.DataFormat; import io.hyperfoil.core.data.Queue; import io.hyperfoil.core.session.ObjectVar; import io.hyperfoil.core.session.SessionFactory; import io.netty.buffer.ByteBuf; public class QueueProcessor implements Processor, ResourceUtilizer { private final ObjectAccess var; private final int maxSize; private final DataFormat format; private final String sequence; private final int concurrency; private final Action onCompletion; private final Session.ResourceKey<Queue> key; public QueueProcessor(Session.ResourceKey<Queue> key, ObjectAccess var, int maxSize, DataFormat format, String sequence, int concurrency, Action onCompletion) { this.key = key; this.var = var; this.maxSize = maxSize; this.format = format; this.sequence = sequence; this.concurrency = concurrency; this.onCompletion = onCompletion; } @Override public void before(Session session) { Queue queue = session.getResource(key); queue.reset(session); } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { ensureDefragmented(isLastPart); Queue queue = session.getResource(key); Object value = format.convert(data, offset, length); queue.push(session, value); } @Override public void after(Session session) { Queue queue = session.getResource(key); queue.producerComplete(session); } @Override public void reserve(Session session) { // If there are multiple concurrent requests all the data end up in single queue; // there's no way to set up different output var so merging them is the only useful behaviour. if (!var.isSet(session)) { var.setObject(session, ObjectVar.newArray(session, concurrency)); } session.declareResource(key, () -> new Queue(var, maxSize, concurrency, sequence, onCompletion), true); } /** * Stores defragmented data in a queue. <br> * For each item in the queue a new sequence instance will be started * (subject the concurrency constraints) with sequence index that allows it to read an object from an array * using sequence-scoped access. */ @MetaInfServices(Processor.Builder.class) @Name("queue") public static class Builder implements Processor.Builder { private String var; private int maxSize; private DataFormat format = DataFormat.STRING; private int concurrency; private String sequence; private Action.Builder onCompletion; private ObjectAccess varAccess; private Queue.Key key; private SequenceBuilder sequenceBuilder; private Consumer<Action.Builder> sequenceCompletion; /** * Variable storing the array that it used as a output object from the queue. * * @param var Variable name. * @return Self. */ public Builder var(String var) { this.var = var; return this; } /** * Maximum number of elements that can be stored in the queue. * * @param maxSize Number of objects. * @return Self. */ public Builder maxSize(int maxSize) { this.maxSize = maxSize; return this; } /** * Conversion format from byte buffers. Default format is STRING. * * @param format Data format. * @return Self. */ public Builder format(DataFormat format) { this.format = format; return this; } /** * Maximum number of started sequences that can be running at one moment. * * @param concurrency Number of sequences. * @return Self. */ public Builder concurrency(int concurrency) { this.concurrency = concurrency; return this; } /** * Name of the started sequence. * * @param sequence Name. * @return Self. */ public Builder sequence(String sequence) { this.sequence = sequence; return this; } public Builder sequence(SequenceBuilder sequenceBuilder, Consumer<Action.Builder> sequenceCompletion) { this.sequenceBuilder = sequenceBuilder; this.sequenceCompletion = sequenceCompletion; return this; } /** * Custom action that should be performed when the last consuming sequence reports that it has processed * the last element from the queue. Note that the sequence is NOT automatically augmented to report completion. * * @return Builder. */ public ServiceLoadedBuilderProvider<Action.Builder> onCompletion() { return new ServiceLoadedBuilderProvider<>(Action.Builder.class, this::onCompletion); } public Builder onCompletion(Action.Builder onCompletion) { this.onCompletion = onCompletion; return this; } @Override public void prepareBuild() { if (var == null) { throw new BenchmarkDefinitionException("Missing 'var' to store the queue."); } varAccess = SessionFactory.objectAccess(var); key = new Queue.Key(); Locator locator = Locator.current(); if (sequence != null && sequenceBuilder != null) { throw new BenchmarkDefinitionException("Cannot set sequence using both name and builder."); } else if (sequence == null && sequenceBuilder == null) { throw new BenchmarkDefinitionException("No sequence was set!"); } if (sequenceBuilder == null) { SequenceBuilder originalSequence = locator.scenario().findSequence(sequence); String generatedSeqName = String.format("%s_queue_%08x", this.sequence, ThreadLocalRandom.current().nextInt()); sequenceBuilder = locator.scenario().sequence(generatedSeqName, originalSequence); } Queue.Key myKey = key; // prevent capturing self reference if (sequenceCompletion == null) { sequenceBuilder.step(s -> { s.getResource(myKey).consumed(s); return true; }); } else { sequenceCompletion.accept(() -> s -> s.getResource(myKey).consumed(s)); } sequenceBuilder.concurrency(concurrency); // We must invoke the prepareBuild() in copied sequences manually sequenceBuilder.prepareBuild(); } @Override public Processor build(boolean fragmented) { if (maxSize <= 0) { throw new BenchmarkDefinitionException("Maximum size for queue to " + var + " must be set!"); } Action completionAction = onCompletion == null ? null : onCompletion.build(); QueueProcessor processor = new QueueProcessor(key, varAccess, maxSize, format, sequenceBuilder.name(), concurrency, completionAction); return fragmented ? new DefragProcessor(processor) : processor; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/StoreIntProcessor.java
core/src/main/java/io/hyperfoil/core/handlers/StoreIntProcessor.java
package io.hyperfoil.core.handlers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.IntAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.impl.Util; import io.netty.buffer.ByteBuf; public class StoreIntProcessor implements Processor { private static final Logger log = LogManager.getLogger(StoreIntProcessor.class); private final IntAccess toVar; private final boolean override; public StoreIntProcessor(IntAccess toVar, boolean override) { this.toVar = toVar; this.override = override; } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { ensureDefragmented(isLastPart); if (toVar.isSet(session) && !override) { log.warn("#{} Variable {} was already set, not setting again.", session.uniqueId(), toVar); } else { try { long value = Util.parseLong(data, offset, length); toVar.setInt(session, (int) value); } catch (NumberFormatException e) { log.warn("#{} Not storing anything because it cannot be parsed to integer: {}", session.uniqueId(), Util.toString(data, offset, length)); } } } /** * Converts buffers into integral value and stores it in a variable. */ @MetaInfServices(Processor.Builder.class) @Name("storeInt") public static class Builder implements Processor.Builder, InitFromParam<Builder> { private String toVar; private boolean override; /** * Name of variable where to store the integral value. * * @param param Name of integer variable where to store the value. * @return Self. */ @Override public Builder init(String param) { return toVar(param); } /** * Name of variable where to store the integral value. * * @param toVar Variable name. * @return Self. */ public Builder toVar(String toVar) { this.toVar = toVar; return this; } /** * Allow the value to be set multiple times (last write wins). Defaults to false. * * @param override Allow override. * @return Self. */ public Builder override(boolean override) { this.override = override; return this; } @Override public Processor build(boolean fragmented) { return DefragProcessor.of(new StoreIntProcessor(SessionFactory.intAccess(toVar), override), fragmented); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/StoreProcessor.java
core/src/main/java/io/hyperfoil/core/handlers/StoreProcessor.java
package io.hyperfoil.core.handlers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.data.DataFormat; import io.hyperfoil.core.session.SessionFactory; import io.netty.buffer.ByteBuf; public class StoreProcessor implements Processor { private static final Logger log = LogManager.getLogger(StoreProcessor.class); private final ObjectAccess toVar; private final DataFormat format; public StoreProcessor(ObjectAccess toVar, DataFormat format) { this.toVar = toVar; this.format = format; } @Override public void before(Session session) { toVar.unset(session); } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { ensureDefragmented(isLastPart); if (toVar.isSet(session)) { log.warn("Variable {} was already set, not setting again.", toVar); } else { Object value = format.convert(data, offset, length); toVar.setObject(session, value); } } /** * Stores data in a session variable (overwriting on multiple occurences). */ @MetaInfServices(Processor.Builder.class) @Name("store") public static class Builder implements Processor.Builder, InitFromParam<Builder> { private Object toVar; private DataFormat format = DataFormat.STRING; /** * @param param Variable name. * @return Self. */ @Override public Builder init(String param) { this.toVar = param; return this; } /** * Variable name. * * @param toVar Variable name. * @return Self. */ public Builder toVar(Object toVar) { this.toVar = toVar; return this; } /** * Format into which should this processor convert the buffers before storing. Default is <code>STRING</code>. * * @param format Data format. * @return Self. */ public Builder format(DataFormat format) { this.format = format; return this; } @Override public Processor build(boolean fragmented) { StoreProcessor storeProcessor = new StoreProcessor(SessionFactory.objectAccess(toVar), format); return fragmented ? new DefragProcessor(storeProcessor) : storeProcessor; } } /** * DEPRECATED: Use <code>store</code> processor instead. */ @MetaInfServices(Processor.Builder.class) @Name("simple") @Deprecated public static class LegacyBuilder extends Builder { } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/DefragTransformer.java
core/src/main/java/io/hyperfoil/core/handlers/DefragTransformer.java
package io.hyperfoil.core.handlers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.processor.Transformer; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.Session; import io.netty.buffer.ByteBuf; import io.netty.buffer.CompositeByteBuf; public class DefragTransformer extends Transformer.BaseDelegating implements ResourceUtilizer, Session.ResourceKey<DefragTransformer.Context> { private static final Logger log = LogManager.getLogger(DefragTransformer.class); public DefragTransformer(Transformer delegate) { super(delegate); } @Override public void transform(Session session, ByteBuf in, int offset, int length, boolean lastFragment, ByteBuf out) { Context ctx = session.getResource(this); if (lastFragment && !ctx.isBuffering()) { delegate.transform(session, in, offset, length, true, out); return; } if (in.isReadable()) { ctx.buffer(in, offset, length); } if (lastFragment) { ctx.flush(session, delegate, out); } } @Override public void reserve(Session session) { // Note: contrary to the recommended pattern the Context won't reserve all objects ahead, the CompositeByteBuf // will be allocated only if needed (and only once). This is necessary since we don't know the type of allocator // that is used for the received buffers ahead. session.declareResource(this, Context::new); } static class Context implements Session.Resource { CompositeByteBuf composite = null; boolean isBuffering() { return composite != null && composite.isReadable(); } public void buffer(ByteBuf data, int offset, int length) { log.debug("Buffering {} bytes", length); if (composite == null) { composite = new CompositeByteBuf(data.alloc(), data.isDirect(), 16); } composite.addComponent(true, data.retainedSlice(offset, length)); } void flush(Session session, Transformer transformer, ByteBuf out) { log.debug("Flushing {} bytes", composite.writerIndex()); transformer.transform(session, composite, 0, composite.writerIndex(), true, out); // Note that processors generally don't modify readerIndex in the ByteBuf // so we cannot expect `data.isReadable() == false` at this point. composite.readerIndex(composite.writerIndex()); composite.discardReadComponents(); } @Override public void destroy() { if (composite != null) { composite.release(); } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/ConditionalProcessor.java
core/src/main/java/io/hyperfoil/core/handlers/ConditionalProcessor.java
package io.hyperfoil.core.handlers; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Embed; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.Condition; import io.hyperfoil.core.builders.ServiceLoadedBuilderProvider; import io.netty.buffer.ByteBuf; public class ConditionalProcessor implements Processor { private final Condition condition; private final Processor[] processors; public ConditionalProcessor(Condition condition, Processor[] processors) { this.condition = condition; this.processors = processors; } @Override public void before(Session session) { if (condition.test(session)) { for (Processor p : processors) { p.before(session); } } } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { if (condition.test(session)) { for (Processor p : processors) { p.process(session, data, offset, length, isLastPart); } } } @Override public void after(Session session) { if (condition.test(session)) { for (Processor p : processors) { p.after(session); } } } /** * Passes the data to nested processor if the condition holds. <br> * Note that the condition may be evaluated multiple times and therefore * any nested processors should not change the results of the condition. */ @MetaInfServices(Processor.Builder.class) @Name("conditional") public static class Builder implements Processor.Builder { private List<Processor.Builder> processors = new ArrayList<>(); private Condition.TypesBuilder<Builder> condition = new Condition.TypesBuilder<>(this); @Embed public Condition.TypesBuilder<Builder> condition() { return condition; } public Builder processor(Processor.Builder processor) { this.processors.add(processor); return this; } public Builder processors(Collection<? extends Processor.Builder> processors) { this.processors.addAll(processors); return this; } /** * One or more processors that should be invoked if the condition holds. * * @return Builder. */ public ServiceLoadedBuilderProvider<Processor.Builder> processor() { return new ServiceLoadedBuilderProvider<>(Processor.Builder.class, this::processor); } @Override public Processor build(boolean fragmented) { if (processors.isEmpty()) { throw new BenchmarkDefinitionException("Conditional processor does not delegate to any processors."); } Condition condition = this.condition.buildCondition(); if (condition == null) { throw new BenchmarkDefinitionException("Conditional processor must specify a condition."); } return new ConditionalProcessor(condition, processors.stream().map(pb -> pb.build(fragmented)).toArray(Processor[]::new)); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/MultiProcessor.java
core/src/main/java/io/hyperfoil/core/handlers/MultiProcessor.java
package io.hyperfoil.core.handlers; import java.util.ArrayList; import java.util.Collection; import java.util.List; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.ServiceLoadedBuilderProvider; import io.netty.buffer.ByteBuf; public class MultiProcessor implements Processor { protected final Processor[] delegates; public MultiProcessor(Processor... delegates) { this.delegates = delegates; } @Override public void before(Session session) { for (Processor p : delegates) { p.before(session); } } @Override public void after(Session session) { for (Processor p : delegates) { p.after(session); } } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { for (Processor p : delegates) { p.process(session, data, offset, length, isLastPart); } } public static class Builder<P, S extends Builder<P, S>> implements Processor.Builder { public final P parent; public final List<Processor.Builder> delegates = new ArrayList<>(); public Builder(P parent) { this.parent = parent; } @SuppressWarnings("unchecked") @Override public Processor build(boolean fragmented) { Processor[] delegates = buildProcessors(fragmented); return new MultiProcessor(delegates); } protected Processor[] buildProcessors(boolean fragmented) { Processor[] delegates = this.delegates.stream().map(d -> d.build(fragmented)).toArray(Processor[]::new); return delegates; } public Processor buildSingle(boolean fragmented) { if (delegates.size() == 1) { return delegates.get(0).build(fragmented); } else { return new MultiProcessor(buildProcessors(fragmented)); } } public S processor(Processor.Builder processor) { delegates.add(processor); return self(); } public S processors(Collection<? extends Processor.Builder> processors) { delegates.addAll(processors); return self(); } /** * Add one or more processors. * * @return Builder. */ public ServiceLoadedBuilderProvider<Processor.Builder> processor() { return new ServiceLoadedBuilderProvider<>(Processor.Builder.class, this::processor); } @SuppressWarnings("unchecked") protected S self() { return (S) this; } public P end() { return parent; } public boolean isEmpty() { return delegates.isEmpty(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/CloseConnectionHandler.java
core/src/main/java/io/hyperfoil/core/handlers/CloseConnectionHandler.java
package io.hyperfoil.core.handlers; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.Session; import io.netty.buffer.ByteBuf; public class CloseConnectionHandler implements Processor { @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { // ignored } @Override public void after(Session session) { session.currentRequest().connection().close(); } /** * Prevents reuse connection after the response has been handled. */ @MetaInfServices(Processor.Builder.class) @Name("closeConnection") public static class Builder implements Processor.Builder { @Override public Processor build(boolean fragmented) { return new CloseConnectionHandler(); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/BaseDelegatingAction.java
core/src/main/java/io/hyperfoil/core/handlers/BaseDelegatingAction.java
package io.hyperfoil.core.handlers; import java.util.ArrayList; import java.util.Collection; import java.util.List; import io.hyperfoil.api.session.Action; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.ServiceLoadedBuilderProvider; public abstract class BaseDelegatingAction implements Action { protected final Action[] actions; public BaseDelegatingAction(Action[] actions) { this.actions = actions; } @Override public void run(Session session) { for (Action a : actions) { a.run(session); } } public abstract static class Builder<S extends Builder<S>> implements Action.Builder { protected final List<Action.Builder> actions = new ArrayList<>(); @SuppressWarnings("unchecked") protected S self() { return (S) this; } public S action(Action.Builder action) { this.actions.add(action); return self(); } public S actions(Collection<? extends Action.Builder> actions) { this.actions.addAll(actions); return self(); } /** * Actions that should be executed should the condition hold. * * @return Builder. */ public ServiceLoadedBuilderProvider<Action.Builder> actions() { return new ServiceLoadedBuilderProvider<>(Action.Builder.class, actions::add); } protected Action[] buildActions() { return actions.stream().map(Action.Builder::build).toArray(Action[]::new); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/NewSequenceAction.java
core/src/main/java/io/hyperfoil/core/handlers/NewSequenceAction.java
package io.hyperfoil.core.handlers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.session.Action; import io.hyperfoil.api.session.Session; public class NewSequenceAction implements Action { private static final Logger log = LogManager.getLogger(NewSequenceAction.class); private final String sequence; private final boolean forceSameIndex; private final Session.ConcurrencyPolicy policy; public NewSequenceAction(String sequence, boolean forceSameIndex, Session.ConcurrencyPolicy policy) { this.sequence = sequence; this.forceSameIndex = forceSameIndex; this.policy = policy; } @Override public void run(Session session) { session.startSequence(sequence, forceSameIndex, policy); } /** * Instantiates a sequence for each invocation. */ @MetaInfServices(Action.Builder.class) @Name("newSequence") public static class Builder implements Action.Builder, InitFromParam<Builder> { private String sequence; private boolean forceSameIndex; private Session.ConcurrencyPolicy policy = Session.ConcurrencyPolicy.FAIL; /** * @param param Sequence name. * @return Self. */ @Override public Builder init(String param) { return sequence(param); } /** * Maximum number of sequences instantiated. * * @param maxSequences Number of sequences. * @return Self. */ @Deprecated @SuppressWarnings("unused") public Builder maxSequences(int maxSequences) { log.warn("Property newSequence.maxSequences is deprecated. Use concurrency setting in target sequence instead."); return this; } /** * Variable storing the counter for sequence IDs. * * @param counterVar Variable name. * @return Self. */ @Deprecated @SuppressWarnings("unused") public Builder counterVar(String counterVar) { log.warn("Property nextSequence.maxSequences is deprecated. Counters are held internally."); return this; } /** * Name of the instantiated sequence. * * @param sequence Sequence name. * @return Self. */ public Builder sequence(String sequence) { this.sequence = sequence; return this; } /** * Forces that the sequence will have the same index as the currently executing sequence. * This can be useful if the sequence is passing some data to the new sequence using sequence-scoped variables. * Note that the new sequence must have same concurrency factor as the currently executing sequence. * * @param force True if the index is forced, false otherwise (default is false). * @return Self. */ public Builder forceSameIndex(boolean force) { this.forceSameIndex = force; return this; } /** * What should we do when the sequence concurrency factor is exceeded. * * @param policy The behaviour. * @return Self. */ public Builder concurrencyPolicy(Session.ConcurrencyPolicy policy) { this.policy = policy; return this; } @Override public NewSequenceAction build() { if (sequence == null) { throw new BenchmarkDefinitionException("Undefined sequence template"); } return new NewSequenceAction(sequence, forceSameIndex, policy); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/GzipInflatorProcessor.java
core/src/main/java/io/hyperfoil/core/handlers/GzipInflatorProcessor.java
package io.hyperfoil.core.handlers; import java.nio.ByteBuffer; import java.util.zip.DataFormatException; import java.util.zip.Inflater; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.logging.log4j.message.FormattedMessage; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.connection.Request; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.session.SessionFactory; import io.netty.buffer.ByteBuf; import io.netty.buffer.ByteBufAllocator; import io.netty.buffer.Unpooled; // Based on java.util.zip.GZIPInputStream public class GzipInflatorProcessor extends MultiProcessor implements ResourceUtilizer, Session.ResourceKey<GzipInflatorProcessor.InflaterResource> { private static final Logger log = LogManager.getLogger(GzipInflatorProcessor.class); private static final int FHCRC = 2; // Header CRC private static final int FEXTRA = 4; // Extra field private static final int FNAME = 8; // File name private static final int FCOMMENT = 16; // File comment private final ReadAccess encodingVar; public GzipInflatorProcessor(Processor[] processors, ReadAccess encodingVar) { super(processors); this.encodingVar = encodingVar; } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { Session.Var var = encodingVar.getVar(session); InflaterResource resource = session.getResource(this); switch (resource.state) { case NOT_ENCRYPTED: super.process(session, data, offset, length, isLastPart); // intentional fallthrough case INVALID: return; case UNINITIALIZED: if (var.isSet() && "gzip".equalsIgnoreCase(var.objectValue(session).toString())) { resource.state = State.FIRST_4_BYTES; // make sure we're starting clear resource.inflater.reset(); } else { resource.state = State.NOT_ENCRYPTED; return; } } resource.process(session, data, offset, length); } @Override public void reserve(Session session) { session.declareResource(this, InflaterResource::new); } public class InflaterResource implements Session.Resource { private final Inflater inflater = new Inflater(true); private State state = State.UNINITIALIZED; private final byte[] buf = new byte[512]; private int bufSize = 0; private final ByteBuf output; private final ByteBuffer nioOutput; private InflaterResource() { output = ByteBufAllocator.DEFAULT.buffer(512); output.writerIndex(output.capacity()); assert output.nioBufferCount() == 1; nioOutput = output.nioBuffer(); } @Override public void destroy() { output.release(); } public void process(Session session, ByteBuf data, int offset, int length) { int read; while (length > 0) { switch (state) { case INVALID: return; case FIRST_4_BYTES: read = Math.min(length, 4 - bufSize); data.getBytes(offset, buf, bufSize, read); bufSize += read; length -= read; offset += read; if (bufSize >= 4) { // verify magic if (Byte.toUnsignedInt(buf[0]) != 0x1F || Byte.toUnsignedInt(buf[1]) != 0x8B) { log.error("#{} Invalid magic bytes at the beginning of the stream", session.uniqueId()); invalidate(session); } else if (Byte.toUnsignedInt(buf[2]) != 8) { log.error("#{} Invalid compression method", session.uniqueId()); invalidate(session); } else { state = State.SKIP_6_BYTES; bufSize = 0; } } break; case SKIP_6_BYTES: read = Math.min(length, 6 - bufSize); bufSize += read; offset += read; length -= read; if (bufSize >= 6) { state = State.CHECK_EXTRA_FIELDS; bufSize = 0; } break; case CHECK_EXTRA_FIELDS: if ((Byte.toUnsignedInt(buf[3]) & FEXTRA) != 0) { read = Math.min(length, 2 - bufSize); data.getBytes(offset, buf, 0, read); bufSize += read; offset += read; length -= read; if (bufSize >= 2) { state = State.SKIP_EXTRA_FIELDS; bufSize = (Byte.toUnsignedInt(buf[1]) << 8) | Byte.toUnsignedInt(buf[0]); } } else { state = State.SKIP_FILENAME; } break; case SKIP_EXTRA_FIELDS: read = Math.min(length, bufSize); offset += read; length -= read; bufSize -= read; if (bufSize == 0) { state = State.SKIP_FILENAME; } break; case SKIP_FILENAME: if ((Byte.toUnsignedInt(buf[3]) & FNAME) != 0) { if (skipZeroTerminated(data, offset, length)) { state = State.SKIP_COMMENT; } } else { state = State.SKIP_COMMENT; } break; case SKIP_COMMENT: if ((Byte.toUnsignedInt(buf[3]) & FCOMMENT) != 0) { if (skipZeroTerminated(data, offset, length)) { state = State.CHECK_HEADER_CRC; } } else { state = State.CHECK_HEADER_CRC; } break; case CHECK_HEADER_CRC: if ((Byte.toUnsignedInt(buf[3]) & FHCRC) != 0) { // this implementation is not checking header CRC read = Math.min(length, 2 - bufSize); bufSize += read; offset += read; length -= read; if (bufSize >= 2) { state = State.DATA; } } else { state = State.DATA; } break; case DATA: try { int n; while ((n = inflater.inflate(nioOutput)) == 0) { if (inflater.needsDictionary()) { log.error("#{} decompression requires a pre-set dictionary but it is not available.", session.uniqueId()); invalidate(session); break; } else if (inflater.finished()) { offset -= inflater.getRemaining(); length += inflater.getRemaining(); inflater.reset(); GzipInflatorProcessor.super.process(session, Unpooled.EMPTY_BUFFER, 0, 0, true); state = State.EOF; bufSize = 8; // read trailers break; // this cycle, not the switch } if (inflater.needsInput()) { if (length == 0) { break; } // Note: we could use nioBuffers for input, too, // but that would cause allocations instead of copying the bytes. read = Math.min(buf.length, length); data.getBytes(offset, buf, 0, read); offset += read; length -= read; inflater.setInput(buf, 0, read); } } if (n != 0) { nioOutput.position(0).limit(output.capacity()); boolean finished = inflater.finished(); GzipInflatorProcessor.super.process(session, output, 0, n, finished); if (finished) { offset -= inflater.getRemaining(); length += inflater.getRemaining(); inflater.reset(); state = State.EOF; bufSize = 8; // read trailers } } } catch (DataFormatException e) { log.error(new FormattedMessage("#{} Failed to decompress GZIPed data.", session.uniqueId()), e); invalidate(session); } break; case EOF: read = Math.min(length, bufSize); offset += read; length -= read; bufSize -= read; if (bufSize == 0) { // inflater is already reset, start a new instance state = State.FIRST_4_BYTES; } break; default: throw new IllegalStateException(state.toString()); } } } private void invalidate(Session session) { Request request = session.currentRequest(); if (request != null) { request.markInvalid(); } state = State.INVALID; } private boolean skipZeroTerminated(ByteBuf data, int offset, int length) { byte b; do { b = data.getByte(offset); offset++; length--; } while (b != 0 && length > 0); return b == 0; } } private enum State { UNINITIALIZED, NOT_ENCRYPTED, INVALID, FIRST_4_BYTES, SKIP_6_BYTES, CHECK_EXTRA_FIELDS, SKIP_EXTRA_FIELDS, SKIP_FILENAME, SKIP_COMMENT, CHECK_HEADER_CRC, DATA, EOF, } /** * Decompresses a GZIP data and pipes the output to delegated processors. <br> * If the data contains multiple concatenated GZIP streams it will pipe multiple decompressed objects * with <code>isLastPart</code> set to true at the end of each stream. */ @MetaInfServices(Processor.Builder.class) @Name("gzipInflator") public static class Builder extends MultiProcessor.Builder<Void, Builder> implements Processor.Builder { private Object encodingVar; public Builder() { super(null); } @Override public Processor build(boolean fragmented) { Processor[] processors = buildProcessors(fragmented); return new GzipInflatorProcessor(processors, SessionFactory.readAccess(encodingVar)); } /** * Variable used to pass header value from header handlers. * * @param var Variable name. * @return Self. */ public Builder encodingVar(Object var) { this.encodingVar = var; return this; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/ArrayRecorder.java
core/src/main/java/io/hyperfoil/core/handlers/ArrayRecorder.java
package io.hyperfoil.core.handlers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.data.DataFormat; import io.hyperfoil.core.session.ObjectVar; import io.hyperfoil.core.session.SessionFactory; import io.netty.buffer.ByteBuf; public class ArrayRecorder implements Processor, ResourceUtilizer { private static final Logger log = LogManager.getLogger(ArrayRecorder.class); private static final boolean trace = log.isTraceEnabled(); private final ObjectAccess toVar; private final DataFormat format; private final int maxSize; private final boolean silent; public ArrayRecorder(ObjectAccess toVar, DataFormat format, int maxSize, boolean silent) { this.toVar = toVar; this.format = format; this.maxSize = maxSize; this.silent = silent; } public void before(Session session) { ObjectVar[] array = (ObjectVar[]) toVar.activate(session); for (int i = 0; i < array.length; ++i) { array[i].unset(); } } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { ensureDefragmented(isLastPart); ObjectVar[] array = (ObjectVar[]) toVar.activate(session); Object value = format.convert(data, offset, length); for (int i = 0; i < array.length; ++i) { if (array[i].isSet()) continue; if (trace) { log.trace("#{} Set {}[{}] <- {}", session.uniqueId(), toVar.toString(), i, value); } array[i].set(value); return; } if (silent) { if (trace) { log.trace("Exceeded maximum size of the array {} ({}), dropping value {}", toVar, maxSize, value); } } else { log.warn("Exceeded maximum size of the array {} ({}), dropping value {}", toVar, maxSize, value); } } @Override public void reserve(Session session) { toVar.setObject(session, ObjectVar.newArray(session, maxSize)); toVar.unset(session); } /** * Stores data in an array stored as session variable. */ @MetaInfServices(Processor.Builder.class) @Name("array") public static class Builder implements Processor.Builder, InitFromParam<Builder> { private String toVar; private DataFormat format = DataFormat.STRING; private int maxSize; private boolean silent; /** * @param param Use format <code>toVar[maxSize]</code>. * @return Self. */ @Override public Builder init(String param) { int b1 = param.indexOf('['); int b2 = param.indexOf(']'); if (b1 < 0 || b2 < 0 || b2 - b1 < 1) { throw new BenchmarkDefinitionException("Array variable must have maximum size: use var[maxSize], e.g. 'foo[16]'"); } try { maxSize = Integer.parseInt(param.substring(b1 + 1, b2)); } catch (NumberFormatException e) { throw new BenchmarkDefinitionException("Cannot parse maximum size in '" + param + "'"); } toVar = param.substring(0, b1).trim(); return this; } @Override public Processor build(boolean fragmented) { return DefragProcessor.of(new ArrayRecorder(SessionFactory.objectAccess(toVar), format, maxSize, silent), fragmented); } /** * Variable name. * * @param var Variable name. * @return Self. */ public Builder toVar(String var) { this.toVar = var; return this; } /** * Maximum size of the array. * * @param maxSize Max number of elements. * @return Self. */ public Builder maxSize(int maxSize) { this.maxSize = maxSize; return this; } /** * Do not log warnings when the maximum size is exceeded. * * @param silent Boolean value. * @return Self. */ public Builder silent(boolean silent) { this.silent = silent; return this; } /** * Format into which should this processor convert the buffers before storing. Default is <code>STRING</code>. * * @param format Data format. * @return Self. */ public Builder format(DataFormat format) { this.format = format; return this; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/CollectionRecorder.java
core/src/main/java/io/hyperfoil/core/handlers/CollectionRecorder.java
package io.hyperfoil.core.handlers; import java.util.ArrayList; import java.util.List; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.ObjectAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.data.DataFormat; import io.hyperfoil.core.session.SessionFactory; import io.netty.buffer.ByteBuf; public class CollectionRecorder implements Processor { private final ObjectAccess toVar; private final DataFormat format; public CollectionRecorder(ObjectAccess toVar, DataFormat format) { this.toVar = toVar; this.format = format; } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { ensureDefragmented(isLastPart); List<Object> list; if (!toVar.isSet(session)) { list = new ArrayList<>(); toVar.setObject(session, list); } else { Object obj = toVar.getObject(session); if (obj instanceof List) { //noinspection unchecked list = (List<Object>) obj; } else { list = new ArrayList<>(); toVar.setObject(session, list); } } list.add(format.convert(data, offset, length)); } /** * Collects results of processor invocation into a unbounded list. <br> * WARNING: This processor should be used rarely as it allocates memory during the benchmark. */ @MetaInfServices(Processor.Builder.class) @Name("collection") public static class Builder implements Processor.Builder, InitFromParam<Builder> { private String toVar; private DataFormat format = DataFormat.STRING; /** * @param param Variable name to store the list. * @return Self. */ @Override public Builder init(String param) { return toVar(param); } /** * Variable name. * * @param var Variable name. * @return Self. */ public Builder toVar(String var) { this.toVar = var; return this; } /** * Format into which should this processor convert the buffers before storing. Default is <code>STRING</code>. * * @param format Data format. * @return Self. */ public Builder format(DataFormat format) { this.format = format; return this; } @Override public Processor build(boolean fragmented) { return DefragProcessor.of(new CollectionRecorder(SessionFactory.objectAccess(toVar), format), fragmented); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/StoreShortcuts.java
core/src/main/java/io/hyperfoil/core/handlers/StoreShortcuts.java
package io.hyperfoil.core.handlers; import io.hyperfoil.api.config.BuilderBase; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.core.data.DataFormat; public class StoreShortcuts<P extends StoreShortcuts.Host> implements BuilderBase<StoreShortcuts<P>> { private final P parent; private DataFormat format = DataFormat.STRING; private String toVar; private String toArray; public interface Host { void accept(Processor.Builder processor); } public StoreShortcuts(P parent) { this.parent = parent; } /** * Conversion to apply on the matching parts with 'toVar' or 'toArray' shortcuts. * * @param format Data format. * @return Self. */ public StoreShortcuts<P> format(DataFormat format) { this.format = format; return this; } /** * Shortcut to store selected parts in an array in the session. Must follow the pattern <code>variable[maxSize]</code> * * @param varAndSize Array name. * @return Self. */ public StoreShortcuts<P> toArray(String varAndSize) { this.toArray = varAndSize; return this; } /** * Shortcut to store first match in given variable. Further matches are ignored. * * @param var Variable name. * @return Self. */ public StoreShortcuts<P> toVar(String var) { this.toVar = var; return this; } public P end() { return parent; } @Override public void prepareBuild() { if (toArray != null) { parent.accept(new ArrayRecorder.Builder().init(toArray).format(format)); } if (toVar != null) { parent.accept(new StoreProcessor.Builder().toVar(toVar).format(format)); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/CountRecorder.java
core/src/main/java/io/hyperfoil/core/handlers/CountRecorder.java
package io.hyperfoil.core.handlers; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.IntAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.session.SessionFactory; import io.netty.buffer.ByteBuf; public class CountRecorder implements Processor { private final IntAccess toVar; public CountRecorder(IntAccess toVar) { this.toVar = toVar; } @Override public void before(Session session) { toVar.setInt(session, 0); } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { if (isLastPart) { toVar.addToInt(session, 1); } } /** * Records number of parts this processor is invoked on. */ @MetaInfServices(Processor.Builder.class) @Name("count") public static class Builder implements Processor.Builder, InitFromParam<Builder> { private String toVar; /** * @param param Name of variable for the number of occurrences. * @return Self. */ @Override public Builder init(String param) { return toVar(param); } /** * Variable where to store number of occurrences. * * @param toVar Variable name. * @return Self. */ public Builder toVar(String toVar) { this.toVar = toVar; return this; } @Override public Processor build(boolean fragmented) { return new CountRecorder(SessionFactory.intAccess(toVar)); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/BaseSearchContext.java
core/src/main/java/io/hyperfoil/core/handlers/BaseSearchContext.java
package io.hyperfoil.core.handlers; import io.hyperfoil.api.session.Session; import io.netty.buffer.ByteBuf; class BaseSearchContext implements Session.Resource { private static final int MAX_PARTS = 16; ByteBuf[] parts = new ByteBuf[MAX_PARTS]; int[] startIndices = new int[MAX_PARTS]; int[] endIndices = new int[MAX_PARTS]; int currentPart = -1; int hashedBytes; int currentHash; static int computeHash(byte[] bytes) { int hash = 0; for (int b : bytes) { hash = 31 * hash + b; } return hash; } static int computeCoef(int length) { int value = 1; for (int i = length; i > 0; --i) { value *= 31; } return value; } void add(ByteBuf data, int offset, int length) { ++currentPart; if (currentPart >= parts.length) { shiftParts(); } parts[currentPart] = data.retain(); startIndices[currentPart] = offset; endIndices[currentPart] = offset + length; } int initHash(int index, int lookupLength) { ByteBuf data = parts[currentPart]; while (index < endIndices[currentPart] && hashedBytes < lookupLength) { currentHash = 31 * currentHash + data.getByte(index++); ++hashedBytes; } return index; } void shiftParts() { parts[0].release(); System.arraycopy(parts, 1, parts, 0, parts.length - 1); System.arraycopy(startIndices, 1, startIndices, 0, startIndices.length - 1); System.arraycopy(endIndices, 1, endIndices, 0, endIndices.length - 1); --currentPart; } int byteRelative(int currentIndex, int numBytesBack) { int part = currentPart; int currentBytesRead = currentIndex - startIndices[part]; if (numBytesBack <= currentBytesRead) { return parts[part].getByte(currentIndex - numBytesBack); } else { numBytesBack -= currentBytesRead; --part; } while (numBytesBack > endIndices[part] - startIndices[part]) { numBytesBack -= endIndices[part] - startIndices[part]; --part; } return parts[part].getByte(endIndices[part] - numBytesBack); } void reset() { hashedBytes = 0; currentHash = 0; currentPart = -1; for (int i = 0; i < parts.length; ++i) { if (parts[i] != null) { parts[i].release(); parts[i] = null; } } } void advance(byte c, int coef, int currentIndex, int numBytesBack) { currentHash = 31 * currentHash + c - coef * byteRelative(currentIndex, numBytesBack); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/DefragProcessor.java
core/src/main/java/io/hyperfoil/core/handlers/DefragProcessor.java
package io.hyperfoil.core.handlers; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.Session; import io.netty.buffer.ByteBuf; import io.netty.buffer.CompositeByteBuf; public class DefragProcessor extends Processor.BaseDelegating implements ResourceUtilizer, Session.ResourceKey<DefragProcessor.Context> { private static final Logger log = LogManager.getLogger(DefragProcessor.class); public static Processor of(Processor delegate, boolean fragmented) { return fragmented ? new DefragProcessor(delegate) : delegate; } public DefragProcessor(Processor delegate) { super(delegate); } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { Context ctx = session.getResource(this); if (isLastPart && !ctx.isBuffering()) { delegate.process(session, data, offset, length, true); return; } if (data.isReadable()) { ctx.buffer(data, offset, length); } if (isLastPart) { ctx.flush(session, delegate); } } @Override public void reserve(Session session) { // Note: contrary to the recommended pattern the Context won't reserve all objects ahead, the CompositeByteBuf // will be allocated only if needed (and only once). This is necessary since we don't know the type of allocator // that is used for the received buffers ahead. session.declareResource(this, Context::new); } static class Context implements Session.Resource { CompositeByteBuf composite = null; boolean isBuffering() { return composite != null && composite.isReadable(); } public void buffer(ByteBuf data, int offset, int length) { log.debug("Buffering {} bytes", length); if (composite == null) { composite = new CompositeByteBuf(data.alloc(), data.isDirect(), 16); } composite.addComponent(true, data.retainedSlice(offset, length)); } void flush(Session session, Processor processor) { log.debug("Flushing {} bytes", composite.writerIndex()); processor.process(session, composite, 0, composite.writerIndex(), true); // Note that processors generally don't modify readerIndex in the ByteBuf // so we cannot expect `data.isReadable() == false` at this point. composite.readerIndex(composite.writerIndex()); composite.discardReadComponents(); } @Override public void destroy() { if (composite != null) { composite.release(); } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/json/ByteArrayByteStream.java
core/src/main/java/io/hyperfoil/core/handlers/json/ByteArrayByteStream.java
package io.hyperfoil.core.handlers.json; import java.util.function.Consumer; import java.util.function.Function; public class ByteArrayByteStream implements ByteStream { private final Function<ByteStream, ByteStream> retain; private final Consumer<ByteStream> release; private byte[] array; private int readerIndex; public ByteArrayByteStream(Function<ByteStream, ByteStream> retain, Consumer<ByteStream> release) { this.retain = retain; this.release = release; } public byte[] array() { return array; } @Override public int getByte(int index) { return array[index]; } @Override public int writerIndex() { return array.length; } @Override public int readerIndex() { return readerIndex; } @Override public void release() { release.accept(this); } @Override public ByteStream retain() { return retain.apply(this); } @Override public void moveTo(ByteStream other) { ByteArrayByteStream o = (ByteArrayByteStream) other; o.array = array; o.readerIndex = readerIndex; array = null; } public ByteArrayByteStream wrap(byte[] array) { this.array = array; this.readerIndex = 0; return this; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/json/ByteStream.java
core/src/main/java/io/hyperfoil/core/handlers/json/ByteStream.java
package io.hyperfoil.core.handlers.json; /** * Abstract wrapper over {@link io.netty.buffer.ByteBuf}, <code>byte[]</code> or {@link String}. */ public interface ByteStream { int getByte(int index); int writerIndex(); int readerIndex(); void release(); ByteStream retain(); void moveTo(ByteStream other); }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/json/JsonHandler.java
core/src/main/java/io/hyperfoil/core/handlers/json/JsonHandler.java
package io.hyperfoil.core.handlers.json; import org.kohsuke.MetaInfServices; import io.hyperfoil.api.config.Name; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.processor.Transformer; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.ServiceLoadedBuilderProvider; import io.netty.buffer.ByteBuf; public class JsonHandler extends JsonParser implements Processor, ResourceUtilizer, Session.ResourceKey<JsonHandler.Context> { public JsonHandler(String query, boolean delete, Transformer replace, Processor processor) { super(query.trim(), delete, replace, processor); } @Override public void before(Session session) { processor.before(session); if (replace != null) { replace.before(session); } } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLast) { if (data.readableBytes() == 0) { return; } Context ctx = session.getResource(this); ctx.parse(ctx.wrap(data, offset, length), session, isLast); } @Override public void after(Session session) { if (replace != null) { replace.after(session); } processor.after(session); Context ctx = session.getResource(this); ctx.reset(); } @Override public String toString() { return "JsonHandler{" + "query='" + query + '\'' + ", recorder=" + processor + '}'; } @Override public void reserve(Session session) { session.declareResource(this, Context::new); } @Override protected void record(JsonParser.Context context, Session session, ByteStream data, int offset, int length, boolean isLastPart) { processor.process(session, ((ByteBufByteStream) data).buffer(), offset, length, isLastPart); } public class Context extends JsonParser.Context { ByteBufByteStream actualStream; Context() { super(self -> new ByteBufByteStream(null, self::release)); actualStream = new ByteBufByteStream(this::retain, null); } public ByteStream wrap(ByteBuf data, int offset, int length) { return actualStream.wrap(data, offset, offset + length); } @Override protected void replaceConsumer(Void ignored, Session session, ByteStream data, int offset, int length, boolean lastFragment) { replace.transform(session, ((ByteBufByteStream) data).buffer(), offset, length, lastFragment, replaceBuffer); } } /** * Parses JSON responses using simple queries. */ @MetaInfServices(Processor.Builder.class) @Name("json") public static class Builder extends BaseBuilder<Builder> implements Processor.Builder { @Override public JsonHandler build(boolean fragmented) { Processor processor = processors.build(fragmented || unquote); Transformer replace = this.replace == null ? null : this.replace.build(fragmented); if (unquote) { processor = new JsonUnquotingTransformer(processor); if (replace != null) { replace = new JsonUnquotingTransformer(replace); } } return new JsonHandler(query, delete, replace, processor); } /** * If neither `delete` or `replace` was set this processor will be called with the selected parts. * In the other case the processor will be called with chunks of full (modified) JSON. * <p> * Note that the `processor.before()` and `processor.after()` methods are called only once for each request, * not for the individual filtered items. * * @return Builder. */ public ServiceLoadedBuilderProvider<Processor.Builder> processor() { return new ServiceLoadedBuilderProvider<>(Processor.Builder.class, processors::processor); } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/json/JsonUnquotingTransformer.java
core/src/main/java/io/hyperfoil/core/handlers/json/JsonUnquotingTransformer.java
package io.hyperfoil.core.handlers.json; import java.nio.charset.StandardCharsets; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.processor.Transformer; import io.hyperfoil.api.session.ResourceUtilizer; import io.hyperfoil.api.session.Session; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; public class JsonUnquotingTransformer implements Transformer, Processor, ResourceUtilizer, Session.ResourceKey<JsonUnquotingTransformer.Context> { private static final ByteBuf NEWLINE = Unpooled.wrappedBuffer("\n".getBytes(StandardCharsets.UTF_8)); private static final ByteBuf BACKSPACE = Unpooled.wrappedBuffer("\b".getBytes(StandardCharsets.UTF_8)); private static final ByteBuf FORMFEED = Unpooled.wrappedBuffer("\f".getBytes(StandardCharsets.UTF_8)); private static final ByteBuf CR = Unpooled.wrappedBuffer("\r".getBytes(StandardCharsets.UTF_8)); private static final ByteBuf TAB = Unpooled.wrappedBuffer("\t".getBytes(StandardCharsets.UTF_8)); protected final Transformer delegate; public JsonUnquotingTransformer(Transformer delegate) { this.delegate = delegate; } public JsonUnquotingTransformer(Processor delegate) { this(new ProcessorAdapter(delegate)); } @Override public void before(Session session) { delegate.before(session); Context context = session.getResource(this); context.reset(); } @Override public void process(Session session, ByteBuf data, int offset, int length, boolean isLastPart) { transform(session, data, offset, length, isLastPart, null); } @Override public void transform(Session session, ByteBuf input, int offset, int length, boolean isLastFragment, ByteBuf output) { Context context = session.getResource(this); int begin; if (context.unicode) { begin = offset + processUnicode(session, input, offset, length, isLastFragment, output, context, 0); } else if (context.first && input.getByte(offset) == '"') { begin = offset + 1; } else { begin = offset; } for (int i = begin - offset; i < length; ++i) { if (context.escaped || input.getByte(offset + i) == '\\') { int fragmentLength = offset + i - begin; if (fragmentLength > 0) { delegate.transform(session, input, begin, fragmentLength, isLastFragment && fragmentLength == length, output); } if (context.escaped) { // This happens when we're starting with chunk escaped in previous chunk context.escaped = false; } else { ++i; if (i >= length) { context.escaped = true; begin = offset + i; break; } } switch (input.getByte(offset + i)) { case 'n': delegate.transform(session, NEWLINE, 0, NEWLINE.readableBytes(), isLastFragment && i == length - 1, output); begin = offset + i + 1; break; case 'b': delegate.transform(session, BACKSPACE, 0, BACKSPACE.readableBytes(), isLastFragment && i == length - 1, output); begin = offset + i + 1; break; case 'f': delegate.transform(session, FORMFEED, 0, FORMFEED.readableBytes(), isLastFragment && i == length - 1, output); begin = offset + i + 1; break; case 'r': delegate.transform(session, CR, 0, CR.readableBytes(), isLastFragment && i == length - 1, output); begin = offset + i + 1; break; case 't': delegate.transform(session, TAB, 0, TAB.readableBytes(), isLastFragment && i == length - 1, output); begin = offset + i + 1; break; case 'u': context.unicode = true; ++i; i = processUnicode(session, input, offset, length, isLastFragment, output, context, i) - 1; begin = offset + i + 1; break; default: // unknown escaped char assert false; case '"': case '/': case '\\': // just skip the escape begin = offset + i; } } else if (isLastFragment && i == length - 1 && input.getByte(offset + i) == '"') { --length; } } context.first = false; int fragmentLength = length - begin + offset; // we need to send this even if the length == 0 as when we have removed the last quote // the previous chunk had not isLastFragment==true delegate.transform(session, input, begin, fragmentLength, isLastFragment, output); if (isLastFragment) { context.reset(); } } private int processUnicode(Session session, ByteBuf data, int offset, int length, boolean isLastPart, ByteBuf output, Context context, int i) { while (i < length && context.unicodeDigits < 4) { context.unicodeChar = context.unicodeChar * 16; byte b = data.getByte(offset + i); if (b >= '0' && b <= '9') { context.unicodeChar += b - '0'; } else if (b >= 'a' && b <= 'f') { context.unicodeChar += 10 + b - 'a'; } else if (b >= 'A' && b <= 'F') { context.unicodeChar += 10 + b - 'A'; } else { // ignore parsing errors as 0 in runtime assert false; } context.unicodeDigits++; ++i; } if (context.unicodeDigits == 4) { // TODO: allocation, probably inefficient... ByteBuf utf8 = Unpooled.wrappedBuffer(Character.toString((char) context.unicodeChar).getBytes(StandardCharsets.UTF_8)); delegate.transform(session, utf8, utf8.readerIndex(), utf8.readableBytes(), isLastPart && i == length - 1, output); context.unicode = false; context.unicodeChar = 0; context.unicodeDigits = 0; } return i; } @Override public void after(Session session) { delegate.after(session); } @Override public void reserve(Session session) { session.declareResource(this, Context::new); } public static class Context implements Session.Resource { private int unicodeDigits; private int unicodeChar; private boolean first = true; private boolean escaped; private boolean unicode; private void reset() { first = true; escaped = false; unicode = false; unicodeDigits = 0; unicodeChar = 0; } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/json/ByteBufByteStream.java
core/src/main/java/io/hyperfoil/core/handlers/json/ByteBufByteStream.java
package io.hyperfoil.core.handlers.json; import java.util.function.Consumer; import java.util.function.Function; import io.netty.buffer.ByteBuf; public class ByteBufByteStream implements ByteStream { private final Function<ByteStream, ByteStream> retain; private final Consumer<ByteStream> release; private ByteBuf buffer; private int readerIndex, writerIndex; public ByteBufByteStream(Function<ByteStream, ByteStream> retain, Consumer<ByteStream> release) { this.retain = retain; this.release = release; } @Override public int getByte(int index) { return buffer.getByte(index); } @Override public int writerIndex() { return writerIndex; } @Override public int readerIndex() { return readerIndex; } @Override public void release() { buffer.release(); buffer = null; readerIndex = -1; release.accept(this); } @Override public ByteStream retain() { buffer.retain(); return retain.apply(this); } @Override public void moveTo(ByteStream other) { ByteBufByteStream o = (ByteBufByteStream) other; assert o.buffer == null; o.buffer = buffer; o.readerIndex = readerIndex; o.writerIndex = writerIndex; buffer = null; readerIndex = -1; } public ByteBuf buffer() { return buffer; } public ByteBufByteStream wrap(ByteBuf data, int readerIndex, int writerIndex) { this.buffer = data; this.readerIndex = readerIndex; this.writerIndex = writerIndex; return this; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/json/StreamQueue.java
core/src/main/java/io/hyperfoil/core/handlers/json/StreamQueue.java
package io.hyperfoil.core.handlers.json; import java.io.Serializable; import java.util.Arrays; import org.jctools.util.Pow2; /** * This serves as an abstraction over several {@link ByteStream bytestreams} so that users can just append * new buffers to the back and use absolute positioning with single index. */ public class StreamQueue { private ByteStream[] parts; // indices used by users for the beginning (readerIndex) of the bytestream private int[] userIndex; private int mask; private int end = -1; private int length = 0; public StreamQueue(int initialCapacity) { initialCapacity = Pow2.roundToPowerOfTwo(initialCapacity); this.mask = initialCapacity - 1; this.parts = new ByteStream[initialCapacity]; this.userIndex = new int[initialCapacity]; Arrays.fill(userIndex, -1); } /** * WARNING: use this only for testing! */ int firstAvailableIndex() { return totalAppendedBytes() - bytes(); } /** * WARNING: use this only for testing! */ int bytes() { int bytes = 0; for (ByteStream part : this.parts) { if (part != null) { bytes += readableBytesOf(part); } } return bytes; } /** * WARNING: use this only for testing! */ int availableCapacityBeforeEnlargement() { // how many nulls from end to tail? if (end == -1) { return parts.length; } else { // how many nulls, including the tail we have till wrapping back to end? int next = next(end); int contiguousNulls = 0; for (int i = 0; i < parts.length; i++) { if (parts[next] != null) { break; } next = next(next); contiguousNulls++; } return contiguousNulls; } } /** * WARNING: use this only for testing! */ int parts() { int count = 0; for (ByteStream part : this.parts) { if (part != null) { count++; } } return count; } private int totalAppendedBytes() { return length; } public int enlargeCapacity(int tail) { assert parts[tail] != null; int newCapacity = Pow2.roundToPowerOfTwo(mask + 2); ByteStream[] newParts = new ByteStream[newCapacity]; int[] newUserIndex = new int[newCapacity]; int secondHalfToCopy = parts.length - tail; System.arraycopy(parts, tail, newParts, 0, secondHalfToCopy); System.arraycopy(userIndex, tail, newUserIndex, 0, secondHalfToCopy); if (tail > 0) { // copy the first part only if needed System.arraycopy(parts, 0, newParts, secondHalfToCopy, tail); System.arraycopy(userIndex, 0, newUserIndex, secondHalfToCopy, tail); } // fill the rest with -1 Arrays.fill(newUserIndex, userIndex.length, newCapacity, -1); mask = newCapacity - 1; end = parts.length - 1; tail = parts.length; userIndex = newUserIndex; // help GC Arrays.fill(parts, null); parts = newParts; assert parts[tail] == null; return tail; } public int append(ByteStream stream) { int tail = next(end); if (parts[tail] != null) { // enlarging capacity can modify end - we need an updated tail tail = enlargeCapacity(tail); } ByteStream retained = stream.retain(); parts[tail] = retained; int newUserIndex = length; userIndex[tail] = newUserIndex; length += readableBytesOf(retained); end = tail; return newUserIndex; } public void releaseUntil(int index) { int i = findPartIndexWith(index); if (i < 0) { return; } assert end >= 0; // Even if index is the last byte accessible within parts[i] we cannot release it too :"( // but we can release the rest i = prev(i); while (hasMoreParts(i)) { releasePart(i); i = prev(i); } } public int getByte(int index) { int i = findPartIndexWith(index); if (i < 0) { return -1; } ByteStream part = parts[i]; int partIndex = partOffset(index, i); if (partIndex >= readableBytesOf(part)) { return -1; } return part.getByte(readerIndexOf(part, partIndex)); } /** * Since parts are ordered based on the starting index they deal with, this search backward from the last appended * one - which contains the highest indexes - to find the part which contains the given index. */ private int findPartIndexWith(int index) { if (index < 0) { return -1; } int i = end; if (i < 0) { return -1; } while (index < userIndex[i]) { i = prev(i); if (!hasMoreParts(i)) { return -1; } } return i; } public void reset() { if (end >= 0) { int i = end; do { releasePart(i); i = prev(i); } while (hasMoreParts(i)); end = -1; } length = 0; } public <P1, P2> void consume(int startIndex, int endIndex, Consumer<P1, P2> consumer, P1 p1, P2 p2, boolean isComplete) { validateIndexes(startIndex, endIndex); if (startIndex == endIndex) { return; } int i = findPartIndexWith(startIndex); if (i < 0) { throw new IllegalArgumentException("Start index " + startIndex + " not found."); } int partStartIndex = partOffset(startIndex, i); boolean isLast = false; while (!isLast) { ByteStream part = parts[i]; final int readableBytes = readableBytesOf(part); final int partEndIndex = partOffset(endIndex, i); isLast = partEndIndex <= readableBytes; final int length; if (isLast) { length = partEndIndex - partStartIndex; } else { length = readableBytes - partStartIndex; } if (length > 0) { consumer.accept(p1, p2, part, readerIndexOf(part, partStartIndex), length, isComplete && isLast); } partStartIndex = 0; i = next(i); } } private static int readableBytesOf(ByteStream stream) { return stream.writerIndex() - stream.readerIndex(); } private static int readerIndexOf(ByteStream part, int partIndex) { return part.readerIndex() + partIndex; } private int partOffset(int streamIndex, int part) { return streamIndex - userIndex[part]; } private void validateIndexes(int startIndex, int endIndex) { if (startIndex < 0 || endIndex < 0) { throw new IllegalArgumentException("Start and end indexes must be non-negative."); } if (startIndex >= length || endIndex > length) { throw new IllegalArgumentException("Start and end indexes must be within the bounds of the stream."); } if (startIndex > endIndex) { throw new IllegalArgumentException("Start index must be less than end index."); } } private int prev(int i) { return (i - 1) & mask; } private int next(int i) { return (i + 1) & mask; } private boolean hasMoreParts(int i) { return i != end && userIndex[i] != -1; } private void releasePart(int i) { userIndex[i] = -1; parts[i].release(); parts[i] = null; } public interface Consumer<P1, P2> extends Serializable { void accept(P1 p1, P2 p2, ByteStream stream, int offset, int length, boolean isLastPart); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/handlers/json/JsonParser.java
core/src/main/java/io/hyperfoil/core/handlers/json/JsonParser.java
package io.hyperfoil.core.handlers.json; import java.io.Serializable; import java.nio.charset.StandardCharsets; import java.util.ArrayDeque; import java.util.ArrayList; import java.util.Arrays; import java.util.function.Function; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.Embed; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Visitor; import io.hyperfoil.api.processor.Processor; import io.hyperfoil.api.processor.Transformer; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.builders.ServiceLoadedBuilderProvider; import io.hyperfoil.core.generators.Pattern; import io.hyperfoil.core.handlers.MultiProcessor; import io.hyperfoil.core.handlers.StoreShortcuts; import io.netty.buffer.ByteBuf; import io.netty.buffer.PooledByteBufAllocator; public abstract class JsonParser implements Serializable { protected static final Logger log = LogManager.getLogger(JsonParser.class); protected static final int INITIAL_PARTS = 16; protected final String query; protected final boolean delete; protected final Transformer replace; protected final Processor processor; @Visitor.Ignore private final JsonParser.Selector[] selectors; @Visitor.Ignore private final StreamQueue.Consumer<Context, Session> record = JsonParser.this::record; public JsonParser(String query, boolean delete, Transformer replace, Processor processor) { this.query = query; this.delete = delete; this.replace = replace; this.processor = processor; byte[] queryBytes = query.getBytes(StandardCharsets.UTF_8); if (queryBytes.length == 0 || queryBytes[0] != '.') { throw new BenchmarkDefinitionException("Path should start with '.'"); } ArrayList<Selector> selectors = new ArrayList<>(); int next = 1; for (int i = 1; i < queryBytes.length; ++i) { if (queryBytes[i] == '[' || queryBytes[i] == '.' && next < i) { while (queryBytes[next] == '.') ++next; if (next != i) { selectors.add(new AttribSelector(Arrays.copyOfRange(queryBytes, next, i))); } next = i + 1; } if (queryBytes[i] == '[') { ArraySelector arraySelector = new ArraySelector(); ++i; int startIndex = i, endIndex = i; for (; i < queryBytes.length; ++i) { if (queryBytes[i] == ']') { if (endIndex < i) { arraySelector.rangeEnd = bytesToInt(queryBytes, startIndex, i); if (startIndex == endIndex) { arraySelector.rangeStart = arraySelector.rangeEnd; } } selectors.add(arraySelector); next = i + 1; break; } else if (queryBytes[i] == ':') { if (startIndex < i) { arraySelector.rangeStart = bytesToInt(queryBytes, startIndex, i); } endIndex = i + 1; } } } } if (next < queryBytes.length) { while (queryBytes[next] == '.') ++next; selectors.add(new AttribSelector(Arrays.copyOfRange(queryBytes, next, queryBytes.length))); } this.selectors = selectors.toArray(new JsonParser.Selector[0]); } protected abstract void record(Context context, Session session, ByteStream data, int offset, int length, boolean isLastPart); private static int bytesToInt(byte[] bytes, int start, int end) { int value = 0; for (;;) { if (bytes[start] < '0' || bytes[start] > '9') { throw new BenchmarkDefinitionException("Invalid range specification: " + new String(bytes)); } value += bytes[start] - '0'; if (++start >= end) { return value; } else { value *= 10; } } } interface Selector extends Serializable { Context newContext(); interface Context { void reset(); } } private static class AttribSelector implements JsonParser.Selector { byte[] name; AttribSelector(byte[] name) { this.name = name; } boolean match(StreamQueue stream, int start, int end) { assert start <= end; // TODO: move this to StreamQueue and optimize access for (int i = 0; i < name.length && i < end - start; ++i) { if (name[i] != stream.getByte(start + i)) return false; } return true; } @Override public Context newContext() { return null; } } private static class ArraySelector implements Selector { int rangeStart = 0; int rangeEnd = Integer.MAX_VALUE; @Override public Context newContext() { return new ArraySelectorContext(); } boolean matches(ArraySelectorContext context) { return context.active && context.currentItem >= rangeStart && context.currentItem <= rangeEnd; } } private static class ArraySelectorContext implements Selector.Context { boolean active; int currentItem; @Override public void reset() { active = false; currentItem = 0; } } protected abstract class Context implements Session.Resource { Selector.Context[] selectorContext = new Selector.Context[selectors.length]; int level; int selectorLevel; int selector; boolean inQuote; boolean inKey; boolean escaped; StreamQueue stream = new StreamQueue(INITIAL_PARTS); int keyStartIndex; int lastCharIndex; // end of key name int valueStartIndex; int lastOutputIndex; // last byte we have written out int safeOutputIndex; // last byte we could definitely write out ArrayDeque<ByteStream> pool = new ArrayDeque<>(INITIAL_PARTS); protected final ByteBuf replaceBuffer = PooledByteBufAllocator.DEFAULT.buffer(); final StreamQueue.Consumer<Void, Session> replaceConsumer = this::replaceConsumer; final Function<Context, ByteStream> byteStreamFactory; protected Context(Function<Context, ByteStream> byteStreamSupplier) { this.byteStreamFactory = byteStreamSupplier; for (int i = 0; i < selectors.length; ++i) { selectorContext[i] = selectors[i].newContext(); } reset(); } public void reset() { for (Selector.Context ctx : selectorContext) { if (ctx != null) ctx.reset(); } level = -1; selectorLevel = 0; selector = 0; inQuote = false; inKey = false; escaped = false; keyStartIndex = -1; lastCharIndex = -1; valueStartIndex = -1; lastOutputIndex = 0; safeOutputIndex = 0; stream.reset(); replaceBuffer.clear(); } @Override public void destroy() { replaceBuffer.release(); stream.reset(); } private Selector.Context current() { return selectorContext[selector]; } public void parse(ByteStream data, Session session, boolean isLast) { final int readableBytes = data.writerIndex() - data.readerIndex(); int readerIndex = stream.append(data); for (int i = 0; i < readableBytes; i++) { int b = stream.getByte(readerIndex++); switch (b) { case -1: throw new IllegalStateException("End of input while the JSON is not complete."); case ' ': case '\n': case '\t': case '\r': // ignore whitespace break; case '\\': escaped = !escaped; break; case '{': if (!inQuote) { ++level; inKey = true; if (valueStartIndex < 0) { safeOutputIndex = readerIndex; } // TODO assert we have active attrib selector } break; case '}': if (!inQuote) { tryRecord(session, readerIndex); if (level == selectorLevel) { --selectorLevel; --selector; } if (valueStartIndex < 0) { safeOutputIndex = readerIndex; } --level; } break; case '"': if (!escaped) { inQuote = !inQuote; } break; case ':': if (!inQuote) { if (selectorLevel == level && keyStartIndex >= 0 && selector < selectors.length && selectors[selector] instanceof AttribSelector) { AttribSelector selector = (AttribSelector) selectors[this.selector]; if (selector.match(stream, keyStartIndex, lastCharIndex)) { if (onMatch(readerIndex) && (delete || replace != null)) { // omit key's starting quote int outputEnd = keyStartIndex - 1; // remove possible comma before the key LOOP: while (true) { switch (stream.getByte(outputEnd - 1)) { case ' ': case '\n': case '\t': case '\r': case ',': --outputEnd; break; default: break LOOP; } } stream.consume(lastOutputIndex, outputEnd, record, this, session, false); lastOutputIndex = outputEnd; } } } keyStartIndex = -1; if (valueStartIndex < 0) { safeOutputIndex = readerIndex; } inKey = false; } break; case ',': if (!inQuote) { inKey = true; keyStartIndex = -1; tryRecord(session, readerIndex); if (selectorLevel == level && selector < selectors.length && current() instanceof ArraySelectorContext) { ArraySelectorContext asc = (ArraySelectorContext) current(); if (asc.active) { asc.currentItem++; } if (((ArraySelector) selectors[selector]).matches(asc)) { if (onMatch(readerIndex) && (delete || replace != null)) { // omit the ',' stream.consume(lastOutputIndex, readerIndex - 1, record, this, session, false); lastOutputIndex = readerIndex - 1; } } } } break; case '[': if (!inQuote) { if (valueStartIndex < 0) { safeOutputIndex = readerIndex; } ++level; if (selectorLevel == level && selector < selectors.length && selectors[selector] instanceof ArraySelector) { ArraySelectorContext asc = (ArraySelectorContext) current(); asc.active = true; if (((ArraySelector) selectors[selector]).matches(asc)) { if (onMatch(readerIndex) && (delete || replace != null)) { stream.consume(lastOutputIndex, readerIndex, record, this, session, false); lastOutputIndex = readerIndex; } } } } break; case ']': if (!inQuote) { tryRecord(session, readerIndex); if (selectorLevel == level && selector < selectors.length && current() instanceof ArraySelectorContext) { ArraySelectorContext asc = (ArraySelectorContext) current(); asc.active = false; --selectorLevel; } if (valueStartIndex < 0) { safeOutputIndex = readerIndex; } keyStartIndex = -1; inKey = false; --level; } break; default: lastCharIndex = readerIndex; if (inKey && keyStartIndex < 0) { keyStartIndex = readerIndex - 1; } } if (b != '\\') { escaped = false; } } if (keyStartIndex >= 0 || valueStartIndex >= 0) { stream.releaseUntil(safeReleaseIndex()); if (isLast) { throw new IllegalStateException("End of input while the JSON is not complete."); } } else { if ((delete || replace != null) && lastOutputIndex < safeOutputIndex) { stream.consume(lastOutputIndex, safeOutputIndex, record, this, session, isLast); lastOutputIndex = safeOutputIndex; } stream.releaseUntil(readerIndex); } } private int safeReleaseIndex() { final int releaseIndex; if (keyStartIndex < 0 && valueStartIndex < 0) { releaseIndex = safeOutputIndex; } else if (keyStartIndex < 0) { assert valueStartIndex >= 0; releaseIndex = Math.min(valueStartIndex, safeOutputIndex); } else if (valueStartIndex < 0) { assert keyStartIndex >= 0; releaseIndex = Math.min(keyStartIndex, safeOutputIndex); } else { releaseIndex = Math.min(Math.min(keyStartIndex, valueStartIndex), safeOutputIndex); } return releaseIndex; } private boolean onMatch(int readerIndex) { ++selector; if (selector < selectors.length) { ++selectorLevel; return false; } else { valueStartIndex = readerIndex; return true; } } private void tryRecord(Session session, int readerIndex) { if (selectorLevel == level && valueStartIndex >= 0) { // valueStartIndex is always before quotes here LOOP: while (true) { switch (stream.getByte(valueStartIndex)) { case ' ': case '\n': case '\r': case '\t': ++valueStartIndex; break; case -1: default: break LOOP; } } int end = readerIndex - 1; LOOP: while (end > valueStartIndex) { switch (stream.getByte(end - 1)) { case ' ': case '\n': case '\r': case '\t': --end; break; default: break LOOP; } } if (valueStartIndex == end) { // This happens when we try to select from a 0-length array // - as long as there are not quotes there's nothing to record. valueStartIndex = -1; --selector; return; } if (replace != null) { // The buffer cannot be overwritten as if the processor is caching input // (this happens when we're defragmenting) we would overwrite the underlying data replaceBuffer.readerIndex(replaceBuffer.writerIndex()); stream.consume(valueStartIndex, end, replaceConsumer, null, session, true); // If the result is empty, don't write the key if (replaceBuffer.isReadable()) { stream.consume(lastOutputIndex, valueStartIndex, record, this, session, false); processor.process(session, replaceBuffer, replaceBuffer.readerIndex(), replaceBuffer.readableBytes(), false); } } else if (!delete) { stream.consume(valueStartIndex, end, record, this, session, true); } lastOutputIndex = end; valueStartIndex = -1; --selector; } } public ByteStream retain(ByteStream stream) { ByteStream pooled = pool.poll(); if (pooled == null) { pooled = byteStreamFactory.apply(this); } stream.moveTo(pooled); return pooled; } public void release(ByteStream stream) { pool.add(stream); } protected abstract void replaceConsumer(Void ignored, Session session, ByteStream data, int offset, int length, boolean lastFragment); } public abstract static class BaseBuilder<S extends BaseBuilder<S>> implements InitFromParam<S>, StoreShortcuts.Host { protected String query; protected boolean unquote = true; protected boolean delete; protected Transformer.Builder replace; protected MultiProcessor.Builder<S, ?> processors = new MultiProcessor.Builder<>(self()); protected StoreShortcuts<S> storeShortcuts = new StoreShortcuts<>(self()); public void accept(Processor.Builder storeProcessor) { processors.processor(storeProcessor); } /** * @param param Either <code>query -&gt; variable</code> or <code>variable &lt;- query</code>. * @return Self. */ @Override public S init(String param) { String query; String var; if (param.contains("->")) { String[] parts = param.split("->"); query = parts[0]; var = parts[1]; } else if (param.contains("<-")) { String[] parts = param.split("->"); query = parts[1]; var = parts[0]; } else { throw new BenchmarkDefinitionException( "Cannot parse json query specification: '" + param + "', use 'query -> var' or 'var <- query'"); } storeShortcuts.toVar(var.trim()); return query(query.trim()); } @SuppressWarnings("unchecked") protected S self() { return (S) this; } /** * Query selecting the part of JSON. * * @param query Query. * @return Self. */ public S query(String query) { this.query = query; return self(); } /** * Automatically unquote and unescape the input values. By default true. * * @param unquote Do unquote and unescape? * @return Builder. */ public S unquote(boolean unquote) { this.unquote = unquote; return self(); } /** * If this is set to true, the selected key will be deleted from the JSON and the modified JSON will be passed * to the <code>processor</code>. * * @param delete Should the selected query be deleted? * @return Self. */ public S delete(boolean delete) { this.delete = delete; return self(); } /** * Custom transformation executed on the value of the selected item. * Note that the output value must contain quotes (if applicable) and be correctly escaped. * * @return Builder. */ public ServiceLoadedBuilderProvider<Transformer.Builder> replace() { return new ServiceLoadedBuilderProvider<>(Transformer.Builder.class, this::replace); } public S replace(Transformer.Builder replace) { if (this.replace != null) { throw new BenchmarkDefinitionException("Calling replace twice!"); } this.replace = replace; return self(); } /** * Replace value of selected item with value generated through a * <a href="https://hyperfoil.io/docs/user-guide/benchmark/variables#string-interpolation">pattern</a>. * Note that the result must contain quotes and be correctly escaped. * * @param pattern Pattern format. * @return Self. */ public S replace(String pattern) { return replace(fragmented -> new Pattern(pattern, false)).unquote(false); } @Embed public MultiProcessor.Builder<S, ?> processors() { return processors; } @Embed public StoreShortcuts<S> storeShortcuts() { return storeShortcuts; } protected void validate() { if (query == null) { throw new BenchmarkDefinitionException("Missing 'query'"); } else if (processors.isEmpty()) { throw new BenchmarkDefinitionException("Missing processor - use 'processor', 'toVar' or 'toArray'"); } } } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/builders/IntConditionBase.java
core/src/main/java/io/hyperfoil/core/builders/IntConditionBase.java
package io.hyperfoil.core.builders; import java.io.Serializable; import io.hyperfoil.api.session.Session; public abstract class IntConditionBase implements Serializable { protected final IntCondition.Predicate predicate; public IntConditionBase(IntCondition.Predicate predicate) { this.predicate = predicate; } public boolean testVar(Session session, Session.Var var) { if (predicate == null) { return true; } if (var.type() == Session.VarType.INTEGER) { return predicate.test(session, var.intValue(session)); } else if (var.type() == Session.VarType.OBJECT) { return testObject(session, var.objectValue(session)); } else { throw new IllegalStateException("Unknown type of var: " + var); } } public boolean testObject(Session session, Object obj) { int value; if (obj instanceof Integer) { value = (Integer) obj; } else if (obj instanceof Long) { long l = (Long) obj; value = (int) Math.min(Math.max(Integer.MIN_VALUE, l), Integer.MAX_VALUE); } else { value = Integer.parseInt(obj.toString()); } return predicate.test(session, value); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/builders/StringConditionBuilder.java
core/src/main/java/io/hyperfoil/core/builders/StringConditionBuilder.java
package io.hyperfoil.core.builders; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.BuilderBase; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.session.ReadAccess; import io.hyperfoil.api.session.Session; import io.hyperfoil.core.session.SessionFactory; import io.hyperfoil.function.SerializableBiPredicate; import io.hyperfoil.impl.Util; public class StringConditionBuilder<B extends StringConditionBuilder<B, P>, P> implements InitFromParam<StringConditionBuilder<B, P>>, BuilderBase<B> { private final P parent; private CharSequence value; private boolean caseSensitive = true; private String matchVar; private CompareMode compareMode; private boolean negate; private LengthBuilder<B, P> length; public StringConditionBuilder(P parent) { this.parent = parent; } public SerializableBiPredicate<Session, CharSequence> buildPredicate() { if (value == null && matchVar == null && length == null) { throw new BenchmarkDefinitionException("Must set one of: 'value', 'startsWith', 'endsWith', 'matchVar' or 'length'!"); } SerializableBiPredicate<Session, CharSequence> predicate = contentPredicate(); if (length != null) { IntCondition.Predicate lengthPredicate = length.buildPredicate(); SerializableBiPredicate<Session, CharSequence> strLengthPredicate = (session, string) -> lengthPredicate.test(session, string == null ? 0 : string.length()); if (predicate == null) { predicate = strLengthPredicate; } else { SerializableBiPredicate<Session, CharSequence> myPredicate = predicate; predicate = (session, string) -> strLengthPredicate.test(session, string) && myPredicate.test(session, string); } } if (predicate == null) { throw new BenchmarkDefinitionException("No condition set in string condition."); } return negate ? predicate.negate() : predicate; } private SerializableBiPredicate<Session, CharSequence> contentPredicate() { CompareMode myCompareMode = compareMode; boolean myCaseSensitive = caseSensitive; if (value != null) { CharSequence myValue = value; return (s, string) -> { int offset = 0, valueLength = myValue.length(); switch (myCompareMode) { case FULL: valueLength = Math.max(string.length(), valueLength); break; case PREFIX: break; case SUFFIX: offset = string.length() - valueLength; break; default: throw new IllegalStateException("Unexpected value: " + myCompareMode); } return myCaseSensitive ? Util.regionMatches(myValue, 0, string, offset, valueLength) : Util.regionMatchesIgnoreCase(myValue, 0, string, offset, valueLength); }; } else if (matchVar != null) { ReadAccess access = SessionFactory.readAccess(matchVar); return (s, string) -> { Object value = access.getObject(s); if (value instanceof CharSequence) { CharSequence v = (CharSequence) value; return myCaseSensitive ? Util.regionMatches(v, 0, string, 0, Math.max(v.length(), string.length())) : Util.regionMatchesIgnoreCase(v, 0, string, 0, Math.max(v.length(), string.length())); } return false; }; } else { return null; } } /** * @param param Literal value the string should match. * @return Self. */ @Override public StringConditionBuilder<B, P> init(String param) { return value(param); } @SuppressWarnings("unchecked") public B self() { return (B) this; } /** * True if the case must match, false if the check is case-insensitive. * * @param caseSensitive Boolean value. * @return Self. */ public B caseSensitive(boolean caseSensitive) { this.caseSensitive = caseSensitive; return self(); } private void ensureNotSet() { if (value != null || matchVar != null) { throw new BenchmarkDefinitionException( "Must set only one of: 'value'/'equalTo', 'notEqualTo', 'startsWith', 'endsWith' or 'matchVar'!"); } } /** * Literal value the string should match. * * @param value String. * @return Self. */ public B value(CharSequence value) { ensureNotSet(); this.value = value; this.compareMode = CompareMode.FULL; return self(); } /** * Literal value the string should match (the same as {@link #value}). * * @param value String. * @return Self. */ public B equalTo(CharSequence value) { return value(value); } /** * Value that the string must not match. * * @param value String. * @return Self. */ public B notEqualTo(CharSequence value) { this.negate = true; return value(value); } /** * Prefix for the string. * * @param value String. * @return Self. */ public B startsWith(CharSequence value) { ensureNotSet(); this.value = value; this.compareMode = CompareMode.PREFIX; return self(); } /** * Suffix for the string. * * @param value String. * @return Self. */ public B endsWith(CharSequence value) { ensureNotSet(); this.value = value; this.compareMode = CompareMode.SUFFIX; return self(); } /** * Fetch the value from a variable. * * @param var Variable name. * @return Self. */ public B matchVar(String var) { ensureNotSet(); this.matchVar = var; return self(); } /** * Invert the logic of this condition. Defaults to false. * * @param negate Use <code>true</code> if the logic should be inverted. * @return Self. */ public B negate(boolean negate) { this.negate = negate; return self(); } /** * Check the length of the string. * * @param exactLength String length. * @return Self. */ public B length(int exactLength) { if (length == null) { length = new LengthBuilder<>(this); } length.equalTo().value(exactLength); return self(); } /** * Check the length of the string. * * @return Builder. */ public LengthBuilder<B, P> length() { if (length == null) { length = new LengthBuilder<>(this); } return length; } public P end() { return parent; } public static class LengthBuilder<B extends StringConditionBuilder<B, P>, P> extends IntConditionBuilder<LengthBuilder<B, P>, StringConditionBuilder<B, P>> { public LengthBuilder(StringConditionBuilder<B, P> parent) { super(parent); } } public enum CompareMode { FULL, PREFIX, SUFFIX } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/builders/ServiceLoadedBuilderProvider.java
core/src/main/java/io/hyperfoil/core/builders/ServiceLoadedBuilderProvider.java
package io.hyperfoil.core.builders; import java.lang.reflect.Constructor; import java.util.ArrayDeque; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.ServiceLoader; import java.util.Set; import java.util.function.Consumer; import java.util.function.Function; import java.util.stream.Stream; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.config.BaseSequenceBuilder; import io.hyperfoil.api.config.BenchmarkDefinitionException; import io.hyperfoil.api.config.IncludeBuilders; import io.hyperfoil.api.config.InitFromParam; import io.hyperfoil.api.config.Name; public class ServiceLoadedBuilderProvider<B> { private static final Logger log = LogManager.getLogger(ServiceLoadedBuilderProvider.class); private static final Map<Class<?>, Map<String, BuilderInfo<?>>> BUILDERS = new HashMap<>(); private final Class<B> builderClazz; private final Consumer<B> consumer; private final BaseSequenceBuilder<?> parent; public static synchronized Map<String, BuilderInfo<?>> builders(Class<?> clazz) { return BUILDERS.computeIfAbsent(clazz, ServiceLoadedBuilderProvider::scanBuilders); } private static Map<String, BuilderInfo<?>> scanBuilders(Class<?> clazz) { Map<String, BuilderInfo<?>> builders = new HashMap<>(); Set<Class<?>> included = new HashSet<>(); ArrayDeque<BuilderInfo<Object>> deque = new ArrayDeque<>(); deque.add(new BuilderInfo<>(clazz, Function.identity())); included.add(clazz); while (!deque.isEmpty()) { BuilderInfo<Object> builderInfo = deque.poll(); ServiceLoader.load(builderInfo.implClazz).stream().forEach(provider -> { Name name = provider.type().getAnnotation(Name.class); if (name == null || name.value().isEmpty()) { log.error("Service-loaded class {} is missing @Name annotation!", provider.type()); } else { // Collisions may exist, e.g. due to different chains of adapters. First match // (the first in breadth-first search, so the closest) wins. builders.putIfAbsent(name.value(), new BuilderInfo<>(provider.type(), builderInfo.adapter)); } }); IncludeBuilders include = builderInfo.implClazz.getAnnotation(IncludeBuilders.class); if (include != null) { for (IncludeBuilders.Conversion conversion : include.value()) { if (!included.contains(conversion.from())) { try { @SuppressWarnings("unchecked") Function<Object, Object> adapter = (Function<Object, Object>) conversion.adapter().getDeclaredConstructor() .newInstance(); // Since we use transitive inclusions through adapters, we have to chain adapters into each other deque.add( new BuilderInfo<>(conversion.from(), builder -> builderInfo.adapter.apply(adapter.apply(builder)))); } catch (Exception e) { throw new IllegalStateException("Cannot instantiate " + conversion.adapter()); } } } } } return builders; } public ServiceLoadedBuilderProvider(Class<B> builderClazz, Consumer<B> consumer) { this(builderClazz, consumer, null); } public ServiceLoadedBuilderProvider(Class<B> builderClazz, Consumer<B> consumer, BaseSequenceBuilder<?> parent) { this.builderClazz = builderClazz; this.consumer = consumer; this.parent = parent; } public ServiceLoadedContract forName(String name, String param) { @SuppressWarnings("unchecked") BuilderInfo<B> builderInfo = (BuilderInfo<B>) builders(builderClazz).get(name); if (builderInfo == null) { throw new BenchmarkDefinitionException(String.format("No builder implementing %s with @Name %s", builderClazz, name)); } try { Object instance = newInstance(builderInfo); if (param != null && !param.isEmpty()) { if (instance instanceof InitFromParam) { ((InitFromParam<?>) instance).init(param); } else { throw new BenchmarkDefinitionException( name + "(" + builderInfo.implClazz + ") cannot be initialized from an inline parameter"); } } return new ServiceLoadedContract(instance, () -> consumer.accept(builderInfo.adapter.apply(instance))); } catch (Exception e) { throw new BenchmarkDefinitionException("Failed to instantiate " + builderInfo.implClazz, e); } } private Object newInstance(BuilderInfo<B> builderInfo) throws InstantiationException, IllegalAccessException, java.lang.reflect.InvocationTargetException { if (parent != null) { Constructor<?> parentCtor = Stream.of(builderInfo.implClazz.getDeclaredConstructors()) .filter(ctor -> ctor.getParameterCount() == 1 && ctor.getParameterTypes()[0] == BaseSequenceBuilder.class) .findFirst().orElse(null); if (parentCtor != null) { return parentCtor.newInstance(parent); } } Constructor<?> noArgCtor = Stream.of(builderInfo.implClazz.getDeclaredConstructors()) .filter(ctor -> ctor.getParameterCount() == 0).findFirst().orElse(null); if (noArgCtor == null) { throw new BenchmarkDefinitionException( "Class " + builderInfo.implClazz.getName() + " does not have a parameterless constructor."); } return noArgCtor.newInstance(); } public interface Owner<B> { ServiceLoadedBuilderProvider<B> serviceLoaded(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/builders/ServiceLoadedContract.java
core/src/main/java/io/hyperfoil/core/builders/ServiceLoadedContract.java
package io.hyperfoil.core.builders; /** * Fill-in the builder provided in {@link #builder()} and then call {@link #complete()}. */ public final class ServiceLoadedContract { private final Object builder; private final Runnable completion; public ServiceLoadedContract(Object builder, Runnable completion) { this.builder = builder; this.completion = completion; } public Object builder() { return builder; } public void complete() { completion.run(); } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false
Hyperfoil/Hyperfoil
https://github.com/Hyperfoil/Hyperfoil/blob/70ad9cad7ba105e88d7c62e7b65892ecd288f034/core/src/main/java/io/hyperfoil/core/builders/BoolConditionBase.java
core/src/main/java/io/hyperfoil/core/builders/BoolConditionBase.java
package io.hyperfoil.core.builders; import java.io.Serializable; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import io.hyperfoil.api.session.Session; import io.hyperfoil.impl.Util; public abstract class BoolConditionBase implements Serializable { private static final Logger log = LogManager.getLogger(BoolConditionBase.class); protected final boolean value; public BoolConditionBase(boolean value) { this.value = value; } public boolean testVar(Session session, Session.Var var) { if (!var.isSet()) { return false; } if (var.type() == Session.VarType.INTEGER) { // this is not C - we won't convert 1 to true, 0 to false return false; } else if (var.type() == Session.VarType.OBJECT) { Object obj = var.objectValue(session); return testObject(obj); } else { throw new IllegalStateException("Unknown type of var: " + var); } } public boolean testObject(Object obj) { if (obj instanceof Boolean) { log.trace("Test boolean {} == {}", obj, value); return (boolean) obj == value; } else if (obj instanceof CharSequence) { CharSequence str = (CharSequence) obj; log.trace("Test string {} equals {}", str, value); if (value) { return Util.regionMatchesIgnoreCase(str, 0, "true", 0, 4); } else { return Util.regionMatchesIgnoreCase(str, 0, "false", 0, 5); } } return false; } }
java
Apache-2.0
70ad9cad7ba105e88d7c62e7b65892ecd288f034
2026-01-05T02:38:03.557103Z
false