@wxn0brp/db-benchmark 0.0.1 → 0.20261124.1745

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.
@@ -0,0 +1,6 @@
1
+ export async function init(action) {
2
+ await action.createIndex("users");
3
+ }
4
+ export async function onAfterAdd(action) {
5
+ await action.createIndex("posts");
6
+ }
@@ -0,0 +1,36 @@
1
+ export async function init(action) {
2
+ const schemas = [
3
+ `
4
+ CREATE TABLE IF NOT EXISTS users (
5
+ _id TEXT PRIMARY KEY,
6
+ name TEXT,
7
+ age INTEGER,
8
+ email TEXT,
9
+ isActive INTEGER,
10
+ createdAt INTEGER
11
+ )`,
12
+ `
13
+ CREATE TABLE IF NOT EXISTS posts (
14
+ _id TEXT PRIMARY KEY,
15
+ title TEXT,
16
+ author TEXT,
17
+ views INTEGER,
18
+ createdAt INTEGER
19
+ )`,
20
+ ];
21
+ for (const sql of schemas) {
22
+ const stmt = await action._prepare(sql);
23
+ await stmt.run();
24
+ }
25
+ await action
26
+ ._prepare("CREATE INDEX IF NOT EXISTS idx_users_isActive ON users(isActive)")
27
+ .then(s => s.run());
28
+ await action
29
+ ._prepare("CREATE INDEX IF NOT EXISTS idx_users_age ON users(age)")
30
+ .then(s => s.run());
31
+ }
32
+ export async function onAfterAdd(action) {
33
+ await action
34
+ ._prepare("CREATE INDEX IF NOT EXISTS idx_posts_views ON posts(views)")
35
+ .then(s => s.run());
36
+ }
package/dist/db.js ADDED
@@ -0,0 +1,9 @@
1
+ import { ValtheraClass } from "@wxn0brp/db-core";
2
+ import { createAdapter } from "@wxn0brp/db-resolver";
3
+ process.env.VALTHERA_MASTER_OPTS = (process.env.VALTHERA_MASTER_OPTS || "[]").replace("$$", Date.now().toString());
4
+ const adapter = await createAdapter({
5
+ name: "master",
6
+ });
7
+ export const db = new ValtheraClass({
8
+ adapter,
9
+ });
@@ -0,0 +1,34 @@
1
+ export function generateUsers(count) {
2
+ const users = new Array(count);
3
+ const now = Date.now();
4
+ for (let i = 0; i < count; i++) {
5
+ users[i] = {
6
+ name: `User_${i}`,
7
+ age: 18 + (i % 50),
8
+ email: `user${i}@example.com`,
9
+ isActive: i % 3 !== 0,
10
+ createdAt: now + i,
11
+ };
12
+ }
13
+ return users;
14
+ }
15
+ export function generatePosts(count) {
16
+ const posts = new Array(count);
17
+ const now = Date.now();
18
+ const authors = [
19
+ "alice",
20
+ "bob",
21
+ "charlie",
22
+ "dave",
23
+ "eve",
24
+ ];
25
+ for (let i = 0; i < count; i++) {
26
+ posts[i] = {
27
+ title: `Post_${i}`,
28
+ author: authors[i % authors.length],
29
+ views: i % 10000,
30
+ createdAt: now + i,
31
+ };
32
+ }
33
+ return posts;
34
+ }
package/dist/index.js ADDED
@@ -0,0 +1,22 @@
1
+ import { db } from "./db.js";
2
+ import { benchmarkLarge } from "./large.js";
3
+ import { benchmarkSmall } from "./small.js";
4
+ import { loadCustomSetup, writeResults } from "./utils.js";
5
+ const adapterName = process.env.VALTHERA_MASTER || "";
6
+ const [pkg] = adapterName.split(":");
7
+ const onAfterAdd = await loadCustomSetup(pkg, db.adapter);
8
+ const allResults = [];
9
+ console.log("small collection (users, 10k)");
10
+ const smallResults = await benchmarkSmall(db.c("users"));
11
+ allResults.push(...smallResults);
12
+ console.log("large collection (posts, 200k)");
13
+ const largeResults = await benchmarkLarge(db.c("posts"), onAfterAdd);
14
+ allResults.push(...largeResults);
15
+ writeResults("result.json", {
16
+ results: allResults,
17
+ adapter: process.env.VALTHERA_MASTER || "N/A",
18
+ coreVersion: db.version,
19
+ adapterVersion: db.adapter?.version || "N/A",
20
+ });
21
+ await db.close();
22
+ setTimeout(() => process.exit(0), 3000).unref(); // exit force after 3 seconds
package/dist/large.js ADDED
@@ -0,0 +1,55 @@
1
+ import { generatePosts } from "./generate.js";
2
+ import { bench } from "./run.js";
3
+ const COUNT = 200_000;
4
+ export async function benchmarkLarge(col, onAfterAdd) {
5
+ const results = [];
6
+ const postData = generatePosts(COUNT);
7
+ const ids = [];
8
+ let i = 0;
9
+ results.push(await bench("add-large", async () => {
10
+ for (const p of postData) {
11
+ const doc = await col.add(p);
12
+ ids.push(doc._id);
13
+ i++;
14
+ if (i % 10000 === 0)
15
+ console.log(`Added ${i} documents`);
16
+ }
17
+ }, COUNT));
18
+ if (onAfterAdd)
19
+ await onAfterAdd();
20
+ const firstId = ids[0];
21
+ const midId = ids[Math.floor(ids.length / 2)];
22
+ const lastId = ids[ids.length - 1];
23
+ results.push(await bench("findOne-large", () => col.findOne({
24
+ _id: firstId,
25
+ })));
26
+ results.push(await bench("find-search-large", () => col.find({
27
+ $gt: {
28
+ views: 9990,
29
+ },
30
+ })));
31
+ results.push(await bench("find-paginated-large", () => col.find({}, {
32
+ limit: 100,
33
+ })));
34
+ results.push(await bench("updateOne-large", () => col.updateOne({
35
+ _id: midId,
36
+ }, {
37
+ views: 999999,
38
+ })));
39
+ results.push(await bench("update-search-large", () => col.update({
40
+ $lt: {
41
+ views: 10,
42
+ },
43
+ }, {
44
+ views: 999999,
45
+ })));
46
+ results.push(await bench("removeOne-large", () => col.removeOne({
47
+ _id: lastId,
48
+ })));
49
+ results.push(await bench("remove-search-large", () => col.remove({
50
+ $gt: {
51
+ views: 9995,
52
+ },
53
+ })));
54
+ return results;
55
+ }
@@ -0,0 +1,51 @@
1
+ import { parseArgs } from "node:util";
2
+ export function printHelp() {
3
+ console.log(`Usage: valthera-bench [adapter] [options]
4
+
5
+ Benchmark a ValtheraDB adapter.
6
+
7
+ Arguments:
8
+ adapter Path to adapter module
9
+ (default: ./valthera-e2e/index.ts)
10
+
11
+ Options:
12
+ -s, --small Run only the small collection benchmark
13
+ -j, --json Save results as JSON
14
+ -f, --jsonFile <path> JSON output file (default: results.json)
15
+ --no-cloud Skip comparison with cloud results
16
+ -h, --help Show this help`);
17
+ }
18
+ export function parseCliOptions() {
19
+ const { values, positionals } = parseArgs({
20
+ options: {
21
+ small: {
22
+ type: "boolean",
23
+ short: "s",
24
+ },
25
+ json: {
26
+ type: "boolean",
27
+ short: "j",
28
+ },
29
+ jsonFile: {
30
+ type: "string",
31
+ short: "f",
32
+ },
33
+ "no-cloud": {
34
+ type: "boolean",
35
+ },
36
+ help: {
37
+ type: "boolean",
38
+ short: "h",
39
+ },
40
+ },
41
+ allowPositionals: true,
42
+ });
43
+ return {
44
+ smallOnly: values.small ?? false,
45
+ jsonOutput: Boolean(values.json || values.jsonFile),
46
+ jsonFile: values.jsonFile || "results.json",
47
+ adapterPathArg: positionals[0] || "./valthera-e2e/index.ts",
48
+ noCloud: values["no-cloud"] ?? false,
49
+ help: values.help ?? false,
50
+ };
51
+ }
@@ -0,0 +1,94 @@
1
+ const REPO = "wxn0brP/ValtheraDB-benchmark";
2
+ const RESULTS_BRANCH = "results";
3
+ function normalize(results) {
4
+ const map = new Map();
5
+ for (const r of results) {
6
+ const arr = map.get(r.name);
7
+ if (arr)
8
+ arr.push(r.time);
9
+ else
10
+ map.set(r.name, [
11
+ r.time,
12
+ ]);
13
+ }
14
+ const out = [];
15
+ for (const [name, times] of map) {
16
+ out.push({
17
+ name,
18
+ time: times.reduce((a, b) => a + b, 0) / times.length,
19
+ });
20
+ }
21
+ return out;
22
+ }
23
+ export async function fetchCloudEntries() {
24
+ const treeRes = await fetch(`https://api.github.com/repos/${REPO}/git/trees/${RESULTS_BRANCH}?recursive=1`, {
25
+ headers: {
26
+ Accept: "application/vnd.github+json",
27
+ },
28
+ });
29
+ if (!treeRes.ok) {
30
+ throw new Error(`GitHub API responded with ${treeRes.status}`);
31
+ }
32
+ const treeData = await treeRes.json();
33
+ const paths = (treeData.tree ?? [])
34
+ .filter((item) => item.path.endsWith("/result.json"))
35
+ .map((item) => item.path);
36
+ return Promise.all(paths.map(async (path) => {
37
+ const res = await fetch(`https://raw.githubusercontent.com/${REPO}/${RESULTS_BRANCH}/${path}`);
38
+ if (!res.ok) {
39
+ throw new Error(`Failed to fetch ${path} (${res.status})`);
40
+ }
41
+ const data = await res.json();
42
+ const dir = path.split("/")[0];
43
+ const [adapter, runtime, os] = dir.split("__");
44
+ return {
45
+ dir,
46
+ adapter,
47
+ runtime,
48
+ os,
49
+ results: normalize(data.results ?? []),
50
+ };
51
+ }));
52
+ }
53
+ function addTimes(map, results) {
54
+ for (const r of results) {
55
+ const arr = map.get(r.name);
56
+ if (arr)
57
+ arr.push(r.time);
58
+ else
59
+ map.set(r.name, [
60
+ r.time,
61
+ ]);
62
+ }
63
+ }
64
+ function toAverages(times) {
65
+ const out = new Map();
66
+ for (const [op, values] of times) {
67
+ out.set(op, {
68
+ avg: values.reduce((a, b) => a + b, 0) / values.length,
69
+ count: values.length,
70
+ });
71
+ }
72
+ return out;
73
+ }
74
+ export function buildCloudAverages(entries) {
75
+ const overallTimes = new Map();
76
+ const adapterTimes = new Map();
77
+ for (const entry of entries) {
78
+ addTimes(overallTimes, entry.results);
79
+ let times = adapterTimes.get(entry.adapter);
80
+ if (!times) {
81
+ times = new Map();
82
+ adapterTimes.set(entry.adapter, times);
83
+ }
84
+ addTimes(times, entry.results);
85
+ }
86
+ const adapters = new Map();
87
+ for (const [adapter, times] of adapterTimes) {
88
+ adapters.set(adapter, toAverages(times));
89
+ }
90
+ return {
91
+ overall: toAverages(overallTimes),
92
+ adapters,
93
+ };
94
+ }
@@ -0,0 +1,79 @@
1
+ import { formatTime } from "./display.js";
2
+ export function buildComparisonRows(localResults, cloud, adapterName) {
3
+ const adapterAvg = cloud.adapters.get(adapterName);
4
+ return localResults.map(r => ({
5
+ op: r.name,
6
+ local: r.time,
7
+ overall: cloud.overall.get(r.name),
8
+ adapter: adapterAvg?.get(r.name),
9
+ }));
10
+ }
11
+ function diff(local, reference) {
12
+ const ratio = local / reference;
13
+ const isTiny = Math.min(local, reference) < 1;
14
+ const equalRatio = isTiny ? 1.25 : 1.05;
15
+ if (ratio >= 1 / equalRatio && ratio <= equalRatio) {
16
+ return {
17
+ text: "≈ equal",
18
+ color: "\x1b[2m",
19
+ };
20
+ }
21
+ if (ratio < 1) {
22
+ return {
23
+ text: `${(1 / ratio).toFixed(2)}x faster`,
24
+ color: "\x1b[32m",
25
+ };
26
+ }
27
+ return {
28
+ text: `${ratio.toFixed(2)}x slower`,
29
+ color: "\x1b[31m",
30
+ };
31
+ }
32
+ function colorCell(d, width) {
33
+ const text = d?.text ?? "-";
34
+ const padded = text.padEnd(width);
35
+ return d ? `${d.color}${padded}\x1b[0m` : padded;
36
+ }
37
+ export function printComparisonTable(rows, adapterName) {
38
+ const adapterHeader = `${adapterName} avg`;
39
+ const localTimes = rows.map(r => formatTime(r.local));
40
+ const overallTimes = rows.map(r => r.overall ? formatTime(r.overall.avg) : "-");
41
+ const adapterTimes = rows.map(r => r.adapter ? formatTime(r.adapter.avg) : "-");
42
+ const overallDiffs = rows.map(r => r.overall ? diff(r.local, r.overall.avg) : null);
43
+ const adapterDiffs = rows.map(r => r.adapter ? diff(r.local, r.adapter.avg) : null);
44
+ const W_OP = Math.max("Test".length, ...rows.map(r => r.op.length));
45
+ const W_LOCAL = Math.max("Local".length, ...localTimes.map(t => t.length));
46
+ const W_OVERALL = Math.max("Overall avg".length, ...overallTimes.map(t => t.length));
47
+ const W_OVERALL_DIFF = Math.max("vs overall".length, ...overallDiffs.map(d => d?.text.length ?? 1));
48
+ const W_ADAPTER = Math.max(adapterHeader.length, ...adapterTimes.map(t => t.length));
49
+ const W_ADAPTER_DIFF = Math.max("vs adapter".length, ...adapterDiffs.map(d => d?.text.length ?? 1));
50
+ const line = (l, m, r) => l +
51
+ "─".repeat(W_OP + 2) +
52
+ m +
53
+ "─".repeat(W_LOCAL + 2) +
54
+ m +
55
+ "─".repeat(W_OVERALL + 2) +
56
+ m +
57
+ "─".repeat(W_OVERALL_DIFF + 2) +
58
+ m +
59
+ "─".repeat(W_ADAPTER + 2) +
60
+ m +
61
+ "─".repeat(W_ADAPTER_DIFF + 2) +
62
+ r;
63
+ const row = (op, local, overall, overallDiff, adapter, adapterDiff) => `│ ${op.padEnd(W_OP)} │ ${local.padStart(W_LOCAL)} │ ${overall.padStart(W_OVERALL)} │ ${colorCell(overallDiff, W_OVERALL_DIFF)} │ ${adapter.padStart(W_ADAPTER)} │ ${colorCell(adapterDiff, W_ADAPTER_DIFF)} │`;
64
+ console.log();
65
+ console.log("\x1b[1m--- Comparison with cloud ---\x1b[0m");
66
+ if (!rows.some(r => r.adapter)) {
67
+ console.log(`\x1b[2m No cloud measurements found for adapter "${adapterName}"\x1b[0m`);
68
+ }
69
+ console.log();
70
+ console.log(line("┌", "┬", "┐"));
71
+ console.log(`│ ${"Test".padEnd(W_OP)} │ ${"Local".padStart(W_LOCAL)} │ ${"Overall avg".padStart(W_OVERALL)} │ ${"vs overall".padEnd(W_OVERALL_DIFF)} │ ${adapterHeader.padStart(W_ADAPTER)} │ ${"vs adapter".padEnd(W_ADAPTER_DIFF)} │`);
72
+ console.log(line("├", "┼", "┤"));
73
+ for (let i = 0; i < rows.length; i++) {
74
+ const r = rows[i];
75
+ console.log(row(r.op, localTimes[i], overallTimes[i], overallDiffs[i], adapterTimes[i], adapterDiffs[i]));
76
+ }
77
+ console.log(line("└", "┴", "┘"));
78
+ console.log();
79
+ }
@@ -0,0 +1,64 @@
1
+ export function formatTime(timeMs) {
2
+ if (timeMs < 1)
3
+ return `${(timeMs * 1000).toFixed(2)}μs`;
4
+ if (timeMs < 1000)
5
+ return `${timeMs.toFixed(2)}ms`;
6
+ return `${(timeMs / 1000).toFixed(2)}s`;
7
+ }
8
+ export function printHeader(adapterName, adapterPath) {
9
+ console.log();
10
+ console.log("──────────────────────────────────────────────────");
11
+ console.log("ValtheraDB Benchmark Runner");
12
+ console.log("──────────────────────────────────────────────────");
13
+ console.log(` Adapter: ${adapterName}`);
14
+ console.log(` Path: ${adapterPath}`);
15
+ console.log(` Date: ${new Date().toISOString()}`);
16
+ console.log("──────────────────────────────────────────────────");
17
+ console.log();
18
+ }
19
+ export function printResultsTable(results) {
20
+ const W_NAME = 25;
21
+ const W_TIME = 10;
22
+ const W_BAR = 25;
23
+ const times = results.map(r => r.time);
24
+ const avg = times.reduce((a, b) => a + b, 0) / times.length;
25
+ const min = Math.min(...times);
26
+ const max = Math.max(...times);
27
+ const logMin = Math.log(min);
28
+ const logRange = Math.log(max) - logMin || 1;
29
+ const line = (l, m, r) => l +
30
+ "─".repeat(W_NAME + 2) +
31
+ m +
32
+ "─".repeat(W_TIME + 2) +
33
+ m +
34
+ "─".repeat(W_BAR + 2) +
35
+ r;
36
+ const row = (a, b, c) => `│ ${a.padEnd(W_NAME)} │ ${b.padStart(W_TIME)} │ ${c.padEnd(W_BAR)} │`;
37
+ const bar = (t) => {
38
+ const pos = (Math.log(t) - logMin) / logRange;
39
+ const len = Math.max(1, Math.round(pos * W_BAR));
40
+ const ratio = t / avg;
41
+ const color = ratio < 0.5 ? "\x1b[32m" : ratio < 2 ? "\x1b[33m" : "\x1b[31m";
42
+ return (color +
43
+ "█".repeat(len) +
44
+ "\x1b[0m" +
45
+ "\x1b[2m" +
46
+ "░".repeat(W_BAR - len) +
47
+ "\x1b[0m");
48
+ };
49
+ console.log();
50
+ console.log(line("┌", "┬", "┐"));
51
+ console.log(row("Test", "Time", "Distribution"));
52
+ console.log(line("├", "┼", "┤"));
53
+ for (const r of results)
54
+ console.log(row(r.name, formatTime(r.time), bar(r.time)));
55
+ console.log(line("└", "┴", "┘"));
56
+ console.log();
57
+ }
58
+ export function printSummary(allResults, adapterName) {
59
+ const totalTime = allResults.reduce((sum, r) => sum + r.time, 0);
60
+ console.log();
61
+ console.log(`\x1b[32m✓\x1b[0m Completed ${allResults.length} benchmarks for ${adapterName}`);
62
+ console.log(` Total time: ${formatTime(totalTime)}`);
63
+ console.log();
64
+ }
@@ -0,0 +1,87 @@
1
+ #!/usr/bin/env bun
2
+ import { ValtheraClass } from "@wxn0brp/db-core";
3
+ import { existsSync } from "fs";
4
+ import { basename, dirname, resolve } from "path";
5
+ import { benchmarkLarge } from "../large.js";
6
+ import { benchmarkSmall } from "../small.js";
7
+ import { loadCustomSetup, writeResults } from "../utils.js";
8
+ import { parseCliOptions, printHelp } from "./args.js";
9
+ import { buildCloudAverages, fetchCloudEntries } from "./cloud.js";
10
+ import { buildComparisonRows, printComparisonTable } from "./compare.js";
11
+ import { printHeader, printResultsTable, printSummary } from "./display.js";
12
+ const options = parseCliOptions();
13
+ if (options.help) {
14
+ printHelp();
15
+ process.exit(0);
16
+ }
17
+ const adapterPath = resolve(process.cwd(), options.adapterPathArg);
18
+ if (!existsSync(adapterPath)) {
19
+ console.error(`Adapter file not found: ${adapterPath}`);
20
+ process.exit(1);
21
+ }
22
+ const pathParts = adapterPath.split("/");
23
+ const valtheraE2eIndex = pathParts.lastIndexOf("valthera-e2e");
24
+ const adapterName = valtheraE2eIndex > 0
25
+ ? pathParts[valtheraE2eIndex - 1]
26
+ : basename(dirname(adapterPath));
27
+ const adapterModule = await import(adapterPath);
28
+ const adapterFactory = adapterModule.default;
29
+ if (typeof adapterFactory !== "function") {
30
+ console.error(`Invalid adapter factory in ${adapterPath}`);
31
+ console.error("Expected default export to be a function");
32
+ process.exit(1);
33
+ }
34
+ printHeader(adapterName, adapterPath);
35
+ console.log(" Loading adapter...");
36
+ const adapter = await adapterFactory();
37
+ if (!adapter) {
38
+ console.error("Adapter factory returned null");
39
+ process.exit(1);
40
+ }
41
+ const db = new ValtheraClass({
42
+ adapter,
43
+ });
44
+ await db.init();
45
+ const onAfterAdd = await loadCustomSetup(adapterName, db.adapter);
46
+ console.log();
47
+ const allResults = [];
48
+ console.log("\x1b[1m--- Small collection (users, 10k) ---\x1b[0m");
49
+ const smallResults = await benchmarkSmall(db.c("users"));
50
+ allResults.push(...smallResults);
51
+ console.log();
52
+ if (!options.smallOnly) {
53
+ console.log("\x1b[1m--- Large collection (posts, 200k) ---\x1b[0m");
54
+ const largeResults = await benchmarkLarge(db.c("posts"), onAfterAdd);
55
+ allResults.push(...largeResults);
56
+ console.log();
57
+ }
58
+ else {
59
+ console.log("\x1b[2m (small-only mode)\x1b[0m");
60
+ }
61
+ console.log("\x1b[1m--- Results ---\x1b[0m");
62
+ printResultsTable(allResults);
63
+ printSummary(allResults, adapterName);
64
+ if (!options.noCloud) {
65
+ console.log(" Loading cloud results...");
66
+ try {
67
+ const cloudEntries = await fetchCloudEntries();
68
+ const cloudAverages = buildCloudAverages(cloudEntries);
69
+ const comparison = buildComparisonRows(allResults, cloudAverages, adapterName);
70
+ printComparisonTable(comparison, adapterName);
71
+ }
72
+ catch (e) {
73
+ console.warn(`\x1b[33m!\x1b[0m Could not load cloud results: ${e.message}`);
74
+ console.warn(" Use --no-cloud to skip this comparison.");
75
+ console.log();
76
+ }
77
+ }
78
+ if (options.jsonOutput) {
79
+ writeResults(options.jsonFile, {
80
+ results: allResults,
81
+ adapter: adapterName,
82
+ coreVersion: db.version,
83
+ adapterVersion: db.adapter?.version || "N/A",
84
+ });
85
+ console.log(`\x1b[2mResults saved to ${options.jsonFile}\x1b[0m`);
86
+ }
87
+ await db.close();
@@ -0,0 +1,30 @@
1
+ import { state } from "./var.js";
2
+ const CACHE_KEY = "benchmark-cache";
3
+ const CACHE_TTL = 10 * 60 * 1000;
4
+ export function loadFromCache() {
5
+ try {
6
+ const raw = localStorage.getItem(CACHE_KEY);
7
+ if (!raw)
8
+ return null;
9
+ const data = JSON.parse(raw);
10
+ if (Date.now() - data.timestamp > CACHE_TTL) {
11
+ localStorage.removeItem(CACHE_KEY);
12
+ return null;
13
+ }
14
+ return data;
15
+ }
16
+ catch {
17
+ return null;
18
+ }
19
+ }
20
+ export function saveToCache() {
21
+ const payload = {
22
+ timestamp: Date.now(),
23
+ ...state,
24
+ };
25
+ localStorage.setItem(CACHE_KEY, JSON.stringify(payload));
26
+ }
27
+ export function clearCache() {
28
+ localStorage.removeItem(CACHE_KEY);
29
+ location.reload();
30
+ }