Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 | import type { Context, DatafileContent } from "@featurevisor/types";
import { createFeaturevisor } from "@featurevisor/sdk";
import type { Featurevisor } from "@featurevisor/sdk";
import { buildRuntimeDatafiles } from "../builder/buildRuntimeDatafiles";
import { Dependencies } from "../dependencies";
import { prettyDuration } from "../tester/prettyDuration";
import { Plugin } from "../cli";
import { getProjectSetExecutions, printSetHeader } from "../sets";
import { CLI_COLOR_CYAN, CLI_FORMAT_BOLD, CLI_FORMAT_GREEN, colorize } from "../tester/cliFormat";
export interface BenchmarkOutput {
value: any;
duration: number; // ms
minDuration: number; // ms
averageDuration: number; // ms
maxDuration: number; // ms
}
function benchmarkEvaluation(n: number, evaluate: () => any): BenchmarkOutput {
let value: any;
let totalDurationNs = 0n;
let minDurationNs: bigint | undefined;
let maxDurationNs = 0n;
for (let i = 0; i < n; i++) {
const start = process.hrtime.bigint();
value = evaluate();
const durationNs = process.hrtime.bigint() - start;
totalDurationNs += durationNs;
if (typeof minDurationNs === "undefined" || durationNs < minDurationNs) {
minDurationNs = durationNs;
}
if (durationNs > maxDurationNs) {
maxDurationNs = durationNs;
}
}
const duration = Number(totalDurationNs) / 1_000_000;
return {
value,
duration,
minDuration: Number(minDurationNs || 0n) / 1_000_000,
averageDuration: duration / n,
maxDuration: Number(maxDurationNs) / 1_000_000,
};
}
function formatDurationMs(duration: number): string {
return `${duration.toFixed(6)}ms`;
}
export function benchmarkFeatureFlag(
f: Featurevisor,
featureKey: string,
context: Record<string, unknown>,
n: number,
): BenchmarkOutput {
return benchmarkEvaluation(n, () => f.isEnabled(featureKey, context as Context));
}
export function benchmarkFeatureVariation(
f: Featurevisor,
featureKey: string,
context: Record<string, unknown>,
n: number,
): BenchmarkOutput {
return benchmarkEvaluation(n, () => f.getVariation(featureKey, context as Context));
}
export function benchmarkFeatureVariable(
f: Featurevisor,
featureKey: string,
variableKey: string,
context: Record<string, unknown>,
n: number,
): BenchmarkOutput {
return benchmarkEvaluation(n, () => f.getVariable(featureKey, variableKey, context as Context));
}
export interface BenchmarkOptions {
environment?: string;
feature: string;
n: number;
context: Record<string, unknown>;
variation?: boolean;
variable?: string;
inflate?: number;
target?: string | string[];
}
async function benchmarkFeatureWithDatafile(
datafileContent: DatafileContent,
options: BenchmarkOptions,
target?: string,
): Promise<void> {
console.log("");
console.log(CLI_FORMAT_BOLD, "Benchmark Featurevisor feature");
console.log(` ${colorize("Feature", CLI_COLOR_CYAN)}: ${options.feature}`);
console.log(` ${colorize("Environment", CLI_COLOR_CYAN)}: ${options.environment || false}`);
if (target) console.log(` ${colorize("Target", CLI_COLOR_CYAN)}: ${target}`);
console.log(` ${colorize("Iterations", CLI_COLOR_CYAN)}: ${options.n}`);
console.log(
` ${colorize("Datafile size", CLI_COLOR_CYAN)}: ${(JSON.stringify(datafileContent).length / 1024).toFixed(2)} kB`,
);
if (options.inflate) {
console.log("");
console.log(
` ${colorize("Features count", CLI_COLOR_CYAN)}: ${Object.keys(datafileContent.features).length}`,
);
console.log(
` ${colorize("Segments count", CLI_COLOR_CYAN)}: ${Object.keys(datafileContent.segments).length}`,
);
}
console.log("");
const f = createFeaturevisor({
datafile: datafileContent as DatafileContent,
logLevel: "warn",
});
console.log(CLI_FORMAT_GREEN, "SDK initialized");
console.log("");
console.log(` ${colorize("Context", CLI_COLOR_CYAN)}: ${JSON.stringify(options.context)}`);
let output: BenchmarkOutput;
if (options.variable) {
// variable
console.log(`Evaluating variable "${options.variable}" ${options.n} times...`);
output = benchmarkFeatureVariable(
f,
options.feature,
options.variable,
options.context,
options.n,
);
} else if (options.variation) {
// variation
console.log(`Evaluating variation ${options.n} times...`);
output = benchmarkFeatureVariation(f, options.feature, options.context, options.n);
} else {
// flag
console.log(`Evaluating flag ${options.n} times...`);
output = benchmarkFeatureFlag(f, options.feature, options.context, options.n);
}
console.log("");
console.log(` ${colorize("Evaluated value", CLI_COLOR_CYAN)}: ${JSON.stringify(output.value)}`);
console.log(
` ${colorize("Total duration", CLI_COLOR_CYAN)}: ${prettyDuration(output.duration)}`,
);
console.log(
` ${colorize("Minimum duration", CLI_COLOR_CYAN)}: ${formatDurationMs(output.minDuration)}`,
);
console.log(
` ${colorize("Average duration", CLI_COLOR_CYAN)}: ${formatDurationMs(output.averageDuration)}`,
);
console.log(
` ${colorize("Maximum duration", CLI_COLOR_CYAN)}: ${formatDurationMs(output.maxDuration)}`,
);
}
export async function benchmarkFeature(
deps: Dependencies,
options: BenchmarkOptions,
): Promise<void> {
const datafileBuildStart = Date.now();
const datafiles = await buildRuntimeDatafiles(deps, {
environment: options.environment || false,
target: options.target,
revision: "include-all-features",
inflate: options.inflate,
});
const datafileBuildDuration = Date.now() - datafileBuildStart;
console.log("");
console.log(`Building ${datafiles.length} datafile${datafiles.length === 1 ? "" : "s"}...`);
console.log(` ${colorize("Build duration", CLI_COLOR_CYAN)}: ${datafileBuildDuration}ms`);
for (const entry of datafiles) {
await benchmarkFeatureWithDatafile(entry.datafile, options, entry.target);
}
}
export const benchmarkPlugin: Plugin = {
command: "benchmark",
handler: async ({ rootDirectoryPath, projectConfig, datasource, parsed }) => {
const executions = await getProjectSetExecutions(projectConfig, datasource, parsed.set);
for (const execution of executions) {
printSetHeader(projectConfig, execution.set);
await benchmarkFeature(
{
rootDirectoryPath,
projectConfig: execution.projectConfig,
datasource: execution.datasource,
options: parsed,
},
{
environment: parsed.environment,
feature: parsed.feature,
n: parseInt(parsed.n, 10) || 1,
context: parsed.context ? JSON.parse(parsed.context) : {},
variation: parsed.variation || undefined,
variable: parsed.variable || undefined,
inflate: parseInt(parsed.inflate, 10) || undefined,
target: parsed.target,
},
);
}
},
examples: [
{
command:
'benchmark --environment=production --feature=my_feature -n=1000 --context=\'{"userId": "123"}\'',
description: "Benchmark a feature flag",
},
{
command:
'benchmark --environment=production --feature=my_feature -n=1000 --context=\'{"userId": "123"}\' --variation',
description: "Benchmark a feature variation",
},
{
command:
'benchmark --environment=production --feature=my_feature -n=1000 --context=\'{"userId": "123"}\' --variable=my-variable',
description: "Benchmark a feature variable",
},
],
};
|