flexi-bench 0.0.0-alpha.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,19 @@
1
+ MIT License
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to deal
5
+ in the Software without restriction, including without limitation the rights
6
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7
+ copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19
+ SOFTWARE.
package/README.md ADDED
File without changes
@@ -0,0 +1,24 @@
1
+ import { Variation } from './variation';
2
+ import { Benchmark } from './benchmark';
3
+ export type MaybePromise<T> = T | Promise<T>;
4
+ export type SetupMethod = (variation: Variation) => MaybePromise<void>;
5
+ export type TeardownMethod = (variation: Variation) => MaybePromise<void>;
6
+ export type ActionMethod = (variation: Variation) => MaybePromise<void>;
7
+ export type EnvironmentVariableOptions = readonly (readonly [key: string, values: readonly string[]])[] | [key: string, values: string[]][];
8
+ export type Result = {
9
+ label: string;
10
+ min: number;
11
+ max: number;
12
+ average: number;
13
+ p95: number;
14
+ };
15
+ export interface ProgressContext {
16
+ totalIterations?: number;
17
+ completedIterations: number;
18
+ timeout?: number;
19
+ timeElapsed: number;
20
+ }
21
+ export interface Reporter {
22
+ progress?: (name: string, progress: number, context: ProgressContext) => void;
23
+ report: (benchmark: Benchmark, results: Result[]) => void;
24
+ }
@@ -0,0 +1,2 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
@@ -0,0 +1,33 @@
1
+ import { Variation } from './variation';
2
+ import { Reporter } from './api-types';
3
+ import { ActionMethod } from './api-types';
4
+ import { TeardownMethod } from './api-types';
5
+ import { SetupMethod } from './api-types';
6
+ export declare class Benchmark {
7
+ name: string;
8
+ private setupMethods;
9
+ private teardownMethods;
10
+ private action?;
11
+ variations: Variation[];
12
+ private iterations?;
13
+ private timeout?;
14
+ private reporter;
15
+ constructor(name: string, options?: {
16
+ setup?: SetupMethod;
17
+ teardown?: TeardownMethod;
18
+ action?: ActionMethod;
19
+ iterations?: number;
20
+ timeout?: number;
21
+ reporter?: Reporter;
22
+ });
23
+ withVariation(name: string, builder: (variation: Variation) => Variation): this;
24
+ withVariations(variations: Variation[]): this;
25
+ withSetup(setup: () => void): this;
26
+ withTeardown(teardown: () => void): this;
27
+ withAction(action: () => void): this;
28
+ withIterations(iterations: number): this;
29
+ withTimeout(timeout: number): this;
30
+ withReporter(reporter: Reporter): this;
31
+ run(): Promise<void>;
32
+ private validate;
33
+ }
@@ -0,0 +1,189 @@
1
+ "use strict";
2
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
3
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
4
+ return new (P || (P = Promise))(function (resolve, reject) {
5
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
6
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
7
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
8
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
9
+ });
10
+ };
11
+ Object.defineProperty(exports, "__esModule", { value: true });
12
+ exports.Benchmark = void 0;
13
+ const console_reporter_1 = require("./console-reporter");
14
+ const variation_1 = require("./variation");
15
+ class Benchmark {
16
+ constructor(name, options) {
17
+ this.name = name;
18
+ this.setupMethods = [];
19
+ this.teardownMethods = [];
20
+ this.variations = [];
21
+ if (options === null || options === void 0 ? void 0 : options.action) {
22
+ this.action = options.action;
23
+ }
24
+ if (options === null || options === void 0 ? void 0 : options.setup) {
25
+ this.setupMethods.push(options.setup);
26
+ }
27
+ if (options === null || options === void 0 ? void 0 : options.teardown) {
28
+ this.teardownMethods.push(options.teardown);
29
+ }
30
+ if (options === null || options === void 0 ? void 0 : options.iterations) {
31
+ this.iterations = options.iterations;
32
+ }
33
+ if (options === null || options === void 0 ? void 0 : options.timeout) {
34
+ this.timeout = options.timeout;
35
+ }
36
+ this.reporter = (options === null || options === void 0 ? void 0 : options.reporter) || new console_reporter_1.ConsoleReporter();
37
+ }
38
+ withVariation(name, builder) {
39
+ this.variations.push(builder(new variation_1.Variation(name)));
40
+ return this;
41
+ }
42
+ withVariations(variations) {
43
+ this.variations.push(...variations);
44
+ return this;
45
+ }
46
+ withSetup(setup) {
47
+ this.setupMethods.push(setup);
48
+ return this;
49
+ }
50
+ withTeardown(teardown) {
51
+ this.teardownMethods.push(teardown);
52
+ return this;
53
+ }
54
+ withAction(action) {
55
+ this.action = action;
56
+ return this;
57
+ }
58
+ withIterations(iterations) {
59
+ this.iterations = iterations;
60
+ return this;
61
+ }
62
+ withTimeout(timeout) {
63
+ this.timeout = timeout;
64
+ return this;
65
+ }
66
+ withReporter(reporter) {
67
+ this.reporter = reporter;
68
+ return this;
69
+ }
70
+ run() {
71
+ return __awaiter(this, void 0, void 0, function* () {
72
+ this.validate();
73
+ let results = [];
74
+ if (this.variations.length === 0) {
75
+ this.variations.push(new variation_1.Variation('default'));
76
+ }
77
+ const totalIterations = this.iterations
78
+ ? this.variations.length * this.iterations
79
+ : undefined;
80
+ const startTime = performance.now();
81
+ let totalCompletedIterations = 0;
82
+ for (let variationIndex = 0; variationIndex < this.variations.length; variationIndex++) {
83
+ const variation = this.variations[variationIndex];
84
+ const timings = [];
85
+ // SETUP
86
+ const oldEnv = Object.assign({}, process.env);
87
+ process.env = Object.assign(Object.assign({}, process.env), variation.environment);
88
+ for (const setup of this.setupMethods) {
89
+ yield setup(variation);
90
+ }
91
+ for (const setup of variation.setupMethods) {
92
+ yield setup(variation);
93
+ }
94
+ // ACT
95
+ const benchmarkThis = this;
96
+ yield new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () {
97
+ let completedIterations = 0;
98
+ let timeout = benchmarkThis.timeout
99
+ ? setTimeout(() => {
100
+ running = false;
101
+ if ((benchmarkThis === null || benchmarkThis === void 0 ? void 0 : benchmarkThis.iterations) &&
102
+ completedIterations < benchmarkThis.iterations) {
103
+ reject('Timeout');
104
+ }
105
+ resolve();
106
+ }, benchmarkThis.timeout)
107
+ : null;
108
+ let running = true;
109
+ while (running) {
110
+ const a = performance.now();
111
+ if (variation.action) {
112
+ yield variation.action(variation);
113
+ }
114
+ else if (this.action) {
115
+ yield this.action(variation);
116
+ }
117
+ const b = performance.now();
118
+ const duration = b - a;
119
+ completedIterations++;
120
+ totalCompletedIterations++;
121
+ timings.push(duration);
122
+ if (this.reporter.progress &&
123
+ totalIterations &&
124
+ benchmarkThis.iterations) {
125
+ this.reporter.progress(variation.name, totalCompletedIterations / totalIterations, {
126
+ timeElapsed: performance.now() - startTime,
127
+ totalIterations,
128
+ completedIterations: totalCompletedIterations,
129
+ timeout: benchmarkThis.timeout,
130
+ });
131
+ }
132
+ if ((benchmarkThis === null || benchmarkThis === void 0 ? void 0 : benchmarkThis.iterations) &&
133
+ completedIterations >= benchmarkThis.iterations) {
134
+ running = false;
135
+ if (timeout) {
136
+ clearTimeout(timeout);
137
+ }
138
+ resolve();
139
+ }
140
+ }
141
+ }));
142
+ if (this.reporter.progress && !totalIterations) {
143
+ this.reporter.progress(variation.name, variationIndex / this.variations.length, {
144
+ timeElapsed: performance.now() - startTime,
145
+ timeout: this.timeout,
146
+ completedIterations: totalCompletedIterations,
147
+ });
148
+ }
149
+ // TEARDOWN
150
+ for (const teardown of variation.teardownMethods) {
151
+ yield teardown(variation);
152
+ }
153
+ for (const teardown of this.teardownMethods) {
154
+ yield teardown(variation);
155
+ }
156
+ process.env = oldEnv;
157
+ // REPORT
158
+ const min = Math.min(...timings);
159
+ const max = Math.max(...timings);
160
+ const sum = timings.reduce((a, b) => a + b, 0);
161
+ const average = sum / timings.length;
162
+ const sortedTimings = [...timings].sort((a, b) => a - b);
163
+ const p95 = sortedTimings[Math.floor(sortedTimings.length * 0.95)];
164
+ results.push({
165
+ label: variation.name,
166
+ min,
167
+ max,
168
+ average,
169
+ p95,
170
+ });
171
+ }
172
+ this.reporter.report(this, results);
173
+ });
174
+ }
175
+ validate() {
176
+ if (!this.action) {
177
+ const missingActions = this.variations.filter((v) => !v.action);
178
+ if (missingActions.length > 0) {
179
+ throw new Error(`Missing action for variations: ${missingActions
180
+ .map((v) => v.name)
181
+ .join(', ')}`);
182
+ }
183
+ else {
184
+ throw new Error(`Benchmark ${this.name} is missing an action`);
185
+ }
186
+ }
187
+ }
188
+ }
189
+ exports.Benchmark = Benchmark;
@@ -0,0 +1,8 @@
1
+ import { Result, Reporter, ProgressContext } from './api-types';
2
+ import { Benchmark } from './benchmark';
3
+ export declare class ConsoleReporter implements Reporter {
4
+ private bar;
5
+ constructor();
6
+ progress(name: string, percent: number, context: ProgressContext): void;
7
+ report(benchmark: Benchmark, results: Result[]): void;
8
+ }
@@ -0,0 +1,31 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ConsoleReporter = void 0;
4
+ const cli_progress_1 = require("cli-progress");
5
+ class ConsoleReporter {
6
+ constructor() {
7
+ this.bar = new cli_progress_1.SingleBar({
8
+ format: 'Running: {label}\n{bar} {percentage}% | {value}/{total} - ETA: {eta}s',
9
+ barCompleteChar: '\u2588',
10
+ barIncompleteChar: '\u2591',
11
+ hideCursor: true,
12
+ });
13
+ }
14
+ progress(name, percent, context) {
15
+ var _a;
16
+ if (!this.bar.isActive) {
17
+ this.bar.start((_a = context.totalIterations) !== null && _a !== void 0 ? _a : 100, 0);
18
+ }
19
+ this.bar.update(context.completedIterations, { label: name });
20
+ process.stdout.moveCursor(0, -1);
21
+ // console.log(`Progress: ${name} ${Math.round(percent * 10000) / 100}%`);
22
+ }
23
+ report(benchmark, results) {
24
+ this.bar.stop();
25
+ process.stdout.moveCursor(0, -1);
26
+ process.stdout.clearScreenDown();
27
+ console.log(`Benchmark: ${benchmark.name}`);
28
+ console.table(results);
29
+ }
30
+ }
31
+ exports.ConsoleReporter = ConsoleReporter;
@@ -0,0 +1,4 @@
1
+ export * from './api-types';
2
+ export * from './benchmark';
3
+ export * from './variation';
4
+ export * from './console-reporter';
package/dist/index.js ADDED
@@ -0,0 +1,20 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./api-types"), exports);
18
+ __exportStar(require("./benchmark"), exports);
19
+ __exportStar(require("./variation"), exports);
20
+ __exportStar(require("./console-reporter"), exports);
@@ -0,0 +1,15 @@
1
+ import { SetupMethod, TeardownMethod, ActionMethod, EnvironmentVariableOptions } from './api-types';
2
+ export declare class Variation {
3
+ name: string;
4
+ setupMethods: SetupMethod[];
5
+ teardownMethods: TeardownMethod[];
6
+ environment: Partial<NodeJS.ProcessEnv>;
7
+ action?: ActionMethod;
8
+ constructor(name: string);
9
+ static FromEnvironmentVariables(variables: EnvironmentVariableOptions): Variation[];
10
+ withSetup(setup: SetupMethod): this;
11
+ withTeardown(teardown: TeardownMethod): this;
12
+ withEnvironmentVariables(env: Partial<NodeJS.ProcessEnv>): this;
13
+ withEnvironmentVariable(name: string, value: string): this;
14
+ withAction(action: ActionMethod): this;
15
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Variation = void 0;
4
+ class Variation {
5
+ constructor(name) {
6
+ this.name = name;
7
+ this.setupMethods = [];
8
+ this.teardownMethods = [];
9
+ this.environment = {};
10
+ }
11
+ static FromEnvironmentVariables(variables) {
12
+ const combinations = variables.reduce((acc, [name, values]) => {
13
+ return acc.flatMap((accItem) => {
14
+ return values.map((value) => {
15
+ return [...accItem, [name, value]];
16
+ });
17
+ });
18
+ }, [[]]);
19
+ return combinations.map((combination) => {
20
+ const label = JSON.stringify(combination);
21
+ return new Variation(label).withEnvironmentVariables(Object.fromEntries(combination));
22
+ });
23
+ }
24
+ withSetup(setup) {
25
+ this.setupMethods.push(setup);
26
+ return this;
27
+ }
28
+ withTeardown(teardown) {
29
+ this.teardownMethods.push(teardown);
30
+ return this;
31
+ }
32
+ withEnvironmentVariables(env) {
33
+ this.environment = Object.assign(Object.assign({}, this.environment), env);
34
+ return this;
35
+ }
36
+ withEnvironmentVariable(name, value) {
37
+ this.environment[name] = value;
38
+ return this;
39
+ }
40
+ withAction(action) {
41
+ this.action = action;
42
+ return this;
43
+ }
44
+ }
45
+ exports.Variation = Variation;
package/package.json ADDED
@@ -0,0 +1,34 @@
1
+ {
2
+ "name": "flexi-bench",
3
+ "version": "0.0.0-alpha.1",
4
+ "description": "",
5
+ "main": "dist/index.js",
6
+ "scripts": {
7
+ "test": "echo \"Error: no test specified\" && exit 1",
8
+ "build": "tsc -p tsconfig.json",
9
+ "format": "prettier --write src"
10
+ },
11
+ "author": "",
12
+ "license": "ISC",
13
+ "devDependencies": {
14
+ "@nx/js": "^19.4.2",
15
+ "@swc-node/register": "~1.9.1",
16
+ "@swc/core": "~1.5.7",
17
+ "@swc/helpers": "~0.5.11",
18
+ "nx": "19.4.2"
19
+ },
20
+ "nx": {},
21
+ "dependencies": {
22
+ "@types/cli-progress": "^3.11.6",
23
+ "@types/node": "^20.14.10",
24
+ "cli-progress": "^3.12.0",
25
+ "prettier": "^3.3.2",
26
+ "typescript": "^5.5.3"
27
+ },
28
+ "files": [
29
+ "dist",
30
+ "README.md",
31
+ "LICENSE",
32
+ "package.json"
33
+ ]
34
+ }