|
| 1 | +package com.flagsmith.flagengine; |
| 2 | + |
| 3 | +import com.fasterxml.jackson.core.json.JsonReadFeature; |
| 4 | +import com.fasterxml.jackson.databind.json.JsonMapper; |
| 5 | +import java.io.BufferedReader; |
| 6 | +import java.io.IOException; |
| 7 | +import java.nio.file.Files; |
| 8 | +import java.nio.file.Path; |
| 9 | +import java.nio.file.Paths; |
| 10 | +import java.util.List; |
| 11 | +import java.util.stream.Collectors; |
| 12 | +import java.util.stream.Stream; |
| 13 | +import org.openjdk.jmh.annotations.Benchmark; |
| 14 | +import org.openjdk.jmh.annotations.Scope; |
| 15 | +import org.openjdk.jmh.annotations.Setup; |
| 16 | +import org.openjdk.jmh.annotations.State; |
| 17 | +import org.openjdk.jmh.infra.Blackhole; |
| 18 | + |
| 19 | +/** |
| 20 | + * Benchmarks local flag evaluation against every engine test data case. |
| 21 | + */ |
| 22 | +@State(Scope.Benchmark) |
| 23 | +public class EngineBenchmark { |
| 24 | + private static final Path testCasesPath = Paths |
| 25 | + .get("src/test/java/com/flagsmith/flagengine/enginetestdata/test_cases"); |
| 26 | + private static final JsonMapper mapper = JsonMapper.builder() |
| 27 | + .enable(JsonReadFeature.ALLOW_JAVA_COMMENTS.mappedFeature()) |
| 28 | + .build(); |
| 29 | + |
| 30 | + private List<EvaluationContext> evaluationContexts; |
| 31 | + |
| 32 | + /** |
| 33 | + * Load the evaluation contexts from the engine test data. |
| 34 | + */ |
| 35 | + @Setup |
| 36 | + public void loadEvaluationContexts() throws IOException { |
| 37 | + try (Stream<Path> paths = Files.walk(testCasesPath)) { |
| 38 | + evaluationContexts = paths |
| 39 | + .filter(Files::isRegularFile) |
| 40 | + .filter(p -> { |
| 41 | + String n = p.getFileName().toString(); |
| 42 | + return n.endsWith(".json") || n.endsWith(".jsonc"); |
| 43 | + }) |
| 44 | + .sorted() |
| 45 | + .map(EngineBenchmark::evaluationContextFromFile) |
| 46 | + .collect(Collectors.toList()); |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + private static EvaluationContext evaluationContextFromFile(Path path) { |
| 51 | + try (BufferedReader reader = Files.newBufferedReader(path)) { |
| 52 | + return mapper.treeToValue(mapper.readTree(reader).get("context"), EvaluationContext.class); |
| 53 | + } catch (IOException e) { |
| 54 | + throw new RuntimeException("Failed to read test data from file: " + path, e); |
| 55 | + } |
| 56 | + } |
| 57 | + |
| 58 | + /** |
| 59 | + * Evaluate flags for every engine test data case. |
| 60 | + */ |
| 61 | + @Benchmark |
| 62 | + public void evaluateEngineTestCases(Blackhole blackhole) { |
| 63 | + for (EvaluationContext evaluationContext : evaluationContexts) { |
| 64 | + blackhole.consume(Engine.getEvaluationResult(evaluationContext)); |
| 65 | + } |
| 66 | + } |
| 67 | +} |
0 commit comments