Files
DMehaffy 19fef31e08 chore(examples): migration performance benchmark harness + mariadb/sqlite + anti-pattern schemas (#26036)
* chore(examples): add mariadb + sqlite + podman support to complex

Extends the complex example's DB tooling to cover all Strapi-supported
database dialects and both container runtimes, as groundwork for a
migration performance benchmark harness:

- New compose.js runtime shim auto-detects podman compose / podman-compose
  / docker compose / docker-compose and the matching container CLI; all
  existing db-* scripts now go through it so podman-only environments
  work without installing docker
- New db-mariadb.js mirrors db-mysql.js using mariadb-dump / mariadb CLIs
  and adds a mariadb:11 service on port 3307 to docker-compose.dev.yml
- New db-sqlite.js handles file-based snapshot/restore/wipe/check via
  fs.copy / better-sqlite3
- db-utils.js falls back to `<runtime> ps --filter name=` for container
  lookup since podman-compose doesn't support `ps -q`
- develop-with-db.js and the v4 templates (develop-with-db.js,
  seed-with-db.js) handle mariadb + sqlite (sqlite skips compose)
- setup-v4-project.js includes better-sqlite3 in v4 deps, database.js
  template covers all 4 clients, and compose.js is copied into the
  v4 scaffold scripts dir (dep of db-utils.js)

All four DBs smoke-tested locally against podman: start/check/snapshot/
restore/wipe cycle works for mariadb; cp-based snapshot cycle works
for sqlite.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore(examples): add migration perf benchmark harness

Three new scripts enable per-migration timing and baseline-vs-candidate
comparison reports for v4→v5 migrations in the complex example:

- bench-hook.js: Node --require preload that intercepts require('umzug')
  and subscribes to Umzug's native `migrating`/`migrated` events for
  sub-ms timing. Captures every migration that runs (including dynamically
  registered ones like discard-drafts and EE-only release migrations)
  without hardcoding names. Dumps to a JSON file on process exit; self-
  disables when STRAPI_BENCH_HOOK_OUTPUT is unset.
- bench.js: orchestrator with `run`, `seed`, and `suite` subcommands.
  `run` restores a snapshot, spawns Strapi in migrate-then-exit mode
  with the hook preload, collects row counts, and writes a result JSON
  with baseline/candidate attribution, env capture (node, CPU, memory,
  DB version, host type), and config (multiplier, seed/hook modes).
  `seed` wipes the DB, runs the v4 seed via seed-with-db.js, then
  snapshots. First iteration supports --strapi-source=local only;
  experimental/pinned are stubbed with a clear error.
- bench-compare.js: takes N labels and emits both a clipboard-friendly
  markdown report (stdout + results/compare-*.md) and a self-contained
  HTML report (results/compare-*.html) with inline SVG bar charts,
  per-DB grid, sortable tables, collapsible raw JSON, and a light/dark
  adaptive theme via prefers-color-scheme. No CDN deps.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore(examples): bench harness smoke-test fixes

Fixes discovered during the end-to-end smoke test on the existing 6
content types at multiplier=1:

- bench-hook.js: switch from subclass-based wrapping to in-place
  Umzug.prototype.up patching. The subclass approach replaced the module
  export at require time, but Node's module cache hands out the original
  class on subsequent requires, so listeners weren't attached on all
  instances. In-place prototype patching works for every instance
  regardless of how Umzug was imported.
- bench-hook.js: flush incrementally after each recorded migration.
  Strapi's shutdown path can bypass process.on('exit') handlers under
  some conditions (signal or explicit exit from deep inside), causing
  fully-collected timing data to be lost. Writing after each recording
  makes the benchmark resilient to any exit path.
- bench.js: compile TypeScript configs via @strapi/typescript-utils
  before createStrapi().load(). The examples/complex project has .ts
  config files; the Strapi CLI compiles them to dist/ before boot but
  our direct node -e loader skipped this, producing
  "db.config.connection undefined" failures.
- bench.js: propagate STRAPI_BENCH_HOOK_DEBUG to the Strapi child so
  debug output is visible when tracing hook behavior.
- bench-compare.js: rework the SVG chart. Dynamic label column sized
  to the longest migration name (up to 420px), 80px reserved on the
  right for value labels so they never clip, inlined monospace font
  (SVG text doesn't reliably inherit CSS variables from the surrounding
  stylesheet), and `dominant-baseline="middle"` for proper vertical
  centering.

Verified: full pipeline (setup:v4 → seed → snapshot → bench:run →
bench:compare) works against postgres at multiplier=1. Ran a baseline
vs cherry-picked PR #25988 comparison — captured all 7 v4→v5 migrations,
produced both markdown and HTML reports with correct test-setup
attribution and delta coloring.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(examples): run ANALYZE before db:check to get fresh row counts

pg_stat_user_tables.n_live_tup and information_schema.tables.table_rows
are approximate and can lag behind reality by minutes or hours depending
on autovacuum / ANALYZE cadence. For a benchmark harness that publishes
row-count numbers in its reports, stale counts are misleading.

Trigger a refresh via ANALYZE (postgres) / ANALYZE TABLE per-table
(mysql/mariadb) before each db:check invocation. Best-effort on the
mysql/mariadb side — fall through to stale stats if ANALYZE fails rather
than error the whole command.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(examples): add hc-m2m-source/target anti-pattern schemas

First anti-pattern schema pair for migration benchmark stress-testing.
A high-cardinality many-to-many relation that forces the v4→v5
discard-drafts migration's copyRelationTableRows code path to span
multiple chunks (>1000 rows) — the same scenario PR #25988's caching
fixes target.

- src/api/hc-m2m-source: collection type with DP and a manyToMany
  relation to hc-m2m-target (owning side)
- src/api/hc-m2m-target: collection type with DP and the inverse
  manyToMany back to source
- setup-v4-project.js: include both in the v4 scaffold CONTENT_TYPES
- seed-v4.js: seedHcM2m() method that creates sources + targets and
  fans out 10 targets-per-source via the M2M relation. BASE counts at
  m=1 are tiny (15 pub + 5 draft per side) but at m=100 produce ~2K
  sources × ~2K targets × 10 = 20K join rows, crossing the 1000-row
  chunk boundary multiple times

Intentionally NOT a realistic content-type design — this is a
stress-test fixture. See the description in schema.json.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat(examples): render multiplier x db matrix in bench-compare

Rework bench-compare to index results by (label, multiplier, dbEngine)
triples pulled from each result JSON's own fields, rather than parsing
labels out of filenames. Lets the same canonical baseline/candidate
label span any number of (multiplier, db) combinations and produces:

- A speedup matrix at the top: rows = multipliers, cols = databases,
  cells = "baseline -> candidate (delta%)". Missing cells render as
  "-" so partial data still produces a useful report.
- A data-availability matrix listing what ran vs what's still missing.
- Per-(db, multiplier) detail sections as collapsible details in
  HTML, all expanded in markdown.

Also:
- New flag syntax: --baseline <label> / --candidate <label>, with
  positional args kept for backward compat.
- Legacy labels that embedded the multiplier (e.g. "baseline-m100")
  are normalized to their base form ("baseline"), letting older
  result files keep working.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(examples): force TCP for mysql/mariadb CLI in containers

The mysql/mariadb CLI tools default to connecting via unix socket at
/var/run/mysqld/mysqld.sock, which isn't populated in the official
mysql:8 / mariadb:11 container images. Every invocation (check,
snapshot, restore, wipe, readiness probe, version probe) needs an
explicit -h 127.0.0.1 to force TCP via the container's loopback.

Without this fix, bench:seed and bench:run error out with
"Can't connect to local MySQL server through socket" on anything
requiring the CLI inside the container (pg_stat-style row-count
queries, snapshot restore, etc.).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* enhancement(examples): parallelize entity creation in seed-v4

Replace sequential for-loops of `await entityService.create(...)` with
a `concurrentMap(count, concurrency, taskFn)` helper that runs N tasks
in flight at once. At SEED_CONCURRENCY=5 (default), a seed that was
strictly serial now fans out into 5 parallel creates.

Concurrency chosen conservatively: Strapi v4's default knex pool is
`{min: 2, max: 10}`, and entity-heavy creates (components + DZs +
localizations) can use multiple connections per call. 5 keeps us well
under the pool ceiling. Tune via `SEED_CONCURRENCY=<n>` env var if
you've also raised the pool max.

Applied to: seedBasic, seedBasicDp, updateComponentRelations,
seedBasicDpI18n, seedRelation, seedRelationDp, seedRelationDpI18n,
seedHcM2m (all entity-creation loops plus their follow-up
self-reference update loops).

Not yet done: incremental seeding (restore previous snapshot + seed
delta) — a separate optimization tracked as a follow-up.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* docs(examples): update complex README for new bench tooling + DBs

README was documenting just the original 6-type, postgres+mysql
workflow. Updated to cover everything this branch adds:

- 8 content types (added hc-m2m-source/target anti-patterns)
- 4 supported databases (added mariadb + sqlite)
- Container runtime auto-detection (podman compose / podman-compose /
  docker compose / docker-compose) with STRAPI_BENCH_RUNTIME override
- Benchmark harness workflow (bench:seed / bench:run / bench:compare /
  bench:suite) for reviewing migration-performance PRs
- SEED_CONCURRENCY, STRAPI_BENCH_HOOK_OUTPUT, STRAPI_BENCH_HOOK_DEBUG,
  and the existing port-override env vars
- MariaDB port default 3307 to avoid colliding with MySQL on 3306

Also collapsed the redundant per-DB command sections (postgres and
mysql both had identical copy-pasted blocks) into a single
'yarn db:<op>:<db>' table since the commands are symmetric across
all four dialects.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix(examples): align better-sqlite3 version with monorepo convention

I picked `11.3.0` arbitrarily. Every other example and tests/app-template
use `12.8.0`, and the root yarn.lock already resolves that version.
Without alignment CI's `yarn install --immutable` fails with 'lockfile
would have been modified', cascading every subsequent job (build, pretty,
commitlint, aggregate_test_result) to red.

Bumping to `12.8.0` to match, regenerating yarn.lock.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: throw instead of return to fail fast

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-authored-by: Ben Irvin <ben@innerdvations.com>
2026-04-27 18:28:08 +02:00

475 lines
17 KiB
JavaScript

#!/usr/bin/env node
/* eslint-disable no-console */
/**
* Migration performance benchmark runner.
*
* Subcommands:
* seed — wipe + boot v4 + seed + snapshot (one-time, expensive)
* run — restore snapshot + run v5 migrations + record timings
* suite — run baseline + candidate across all 4 DBs (chained runs)
*
* Strapi source resolution (currently only `local` is implemented):
* local — use the monorepo workspace-linked @strapi/*
* To swap between branches: git checkout <branch> && yarn bench:run
* experimental — install 0.0.0-experimental.<sha> into .bench-install/<ver>/
* (NOT YET IMPLEMENTED — error thrown)
* pinned — install a specific published version (NOT YET IMPLEMENTED)
*/
const { execSync, spawnSync, spawn } = require('child_process');
const fs = require('fs');
const os = require('os');
const path = require('path');
const { getDatabaseEnv } = require('./db-utils');
const SCRIPT_DIR = __dirname;
const COMPLEX_DIR = path.resolve(SCRIPT_DIR, '..');
const MONOREPO_ROOT = path.resolve(COMPLEX_DIR, '../..');
const RESULTS_DIR = path.join(COMPLEX_DIR, 'results');
const V4_PROJECT_DIR = process.env.V4_OUTSIDE_DIR
? path.resolve(process.cwd(), process.env.V4_OUTSIDE_DIR)
: path.resolve(MONOREPO_ROOT, '..', 'complex-v4');
const SUPPORTED_DBS = ['postgres', 'mysql', 'mariadb', 'sqlite'];
// ─── arg parsing ──────────────────────────────────────────────────────────────
function parseArgs(argv) {
const out = {};
for (let i = 0; i < argv.length; i += 1) {
const arg = argv[i];
if (!arg.startsWith('--')) continue;
const eq = arg.indexOf('=');
if (eq !== -1) {
out[arg.slice(2, eq)] = arg.slice(eq + 1);
continue;
}
const next = argv[i + 1];
if (next == null || next.startsWith('--')) {
out[arg.slice(2)] = true;
} else {
out[arg.slice(2)] = next;
i += 1;
}
}
return out;
}
function requireArg(args, name, fallback) {
const v = args[name] ?? fallback;
if (v == null || v === '') {
console.error(`Error: --${name} is required`);
process.exit(1);
}
return v;
}
// ─── environment capture ──────────────────────────────────────────────────────
function captureEnv(db) {
const envInfo = {
nodeVersion: process.version,
platform: process.platform,
arch: process.arch,
cpuModel: os.cpus()[0]?.model || 'unknown',
cpuCount: os.cpus().length,
totalMemMB: Math.round(os.totalmem() / (1024 * 1024)),
dbEngine: db,
dbVersion: null,
dbHostType: db === 'sqlite' ? 'local-file' : 'local-container',
};
// Best-effort DB version probe — don't fail the benchmark if this breaks.
try {
if (db === 'sqlite') {
// eslint-disable-next-line global-require
const Database = require('better-sqlite3');
envInfo.dbVersion = Database.prototype.constructor.name
? require('better-sqlite3/package.json').version
: null;
} else {
const { runContainer } = require('./compose');
const containerLookup = {
postgres: ['ps', '--filter', 'name=strapi_complex_postgres', '--format', '{{.ID}}'],
mysql: ['ps', '--filter', 'name=strapi_complex_mysql', '--format', '{{.ID}}'],
mariadb: ['ps', '--filter', 'name=strapi_complex_mariadb', '--format', '{{.ID}}'],
};
const idRaw = runContainer(containerLookup[db]).trim();
const id = idRaw.split('\n').filter(Boolean)[0];
if (id) {
// Force TCP (-h 127.0.0.1) for mysql/mariadb because their CLIs default
// to a unix-socket path that doesn't exist in the official images.
const probeCmd = {
postgres: ['exec', id, 'psql', '-U', 'strapi', '-t', '-c', 'SHOW server_version;'],
mysql: [
'exec',
id,
'mysql',
'-h',
'127.0.0.1',
'-ustrapi',
'-pstrapi',
'-sN',
'-e',
'SELECT VERSION();',
],
mariadb: [
'exec',
id,
'mariadb',
'-h',
'127.0.0.1',
'-ustrapi',
'-pstrapi',
'-sN',
'-e',
'SELECT VERSION();',
],
};
envInfo.dbVersion = runContainer(probeCmd[db]).trim().split('\n')[0];
}
}
} catch (err) {
envInfo.dbVersionProbeError = String(err.message || err);
}
return envInfo;
}
function captureStrapiSource() {
// Read @strapi/strapi version actually resolved (so `local` reports the
// monorepo's current version + branch + sha).
let version = null;
try {
// eslint-disable-next-line global-require
version = require('@strapi/strapi/package.json').version;
} catch {
/* leave null */
}
let gitSha = null;
let gitBranch = null;
try {
gitSha = execSync('git rev-parse HEAD', { cwd: MONOREPO_ROOT, encoding: 'utf8' }).trim();
} catch {
/* leave null */
}
try {
gitBranch = execSync('git rev-parse --abbrev-ref HEAD', {
cwd: MONOREPO_ROOT,
encoding: 'utf8',
}).trim();
} catch {
/* leave null */
}
return {
strapiSource: 'local',
strapiVersion: version,
strapiGitSha: gitSha,
strapiGitBranch: gitBranch,
};
}
// ─── snapshot helpers ─────────────────────────────────────────────────────────
function snapshotExists(db, name) {
if (db === 'sqlite') {
return fs.existsSync(path.join(COMPLEX_DIR, 'snapshots', `sqlite-${name}.db`));
}
return fs.existsSync(path.join(COMPLEX_DIR, 'snapshots', `${db}-${name}.sql`));
}
function restoreSnapshot(db, name) {
const script = `db-${db}.js`;
console.log(`Restoring ${db} snapshot "${name}"...`);
execSync(`node ${path.join('scripts', script)} restore ${name}`, {
cwd: COMPLEX_DIR,
stdio: 'inherit',
});
}
// ─── row count collection ─────────────────────────────────────────────────────
function collectRowCounts(db) {
const script = `db-${db}.js`;
try {
const output = execSync(`node ${path.join('scripts', script)} check`, {
cwd: COMPLEX_DIR,
encoding: 'utf8',
});
// Parse the "Table Name | Row Count" table produced by db:check.
const rowCounts = {};
const lines = output.split('\n');
let inTable = false;
for (const line of lines) {
if (line.includes('---|')) {
inTable = true;
continue;
}
if (!inTable) continue;
const m = line.match(/^([^|]+?)\s*\|\s*(\d+)\s*$/);
if (m) rowCounts[m[1].trim()] = Number(m[2]);
}
return rowCounts;
} catch (err) {
return { _error: String(err.message || err) };
}
}
// ─── migrate-then-exit runner ─────────────────────────────────────────────────
/**
* Spawn Strapi, wait for it to finish bootstrapping (which runs migrations),
* then cleanly tear down. Uses the bench-hook preload to capture timings.
*/
function runMigrationsOnce(db, hookOutputPath) {
const env = {
...getDatabaseEnv(db),
STRAPI_BENCH_HOOK_OUTPUT: hookOutputPath,
STRAPI_BENCH_HOOK_DEBUG: process.env.STRAPI_BENCH_HOOK_DEBUG || '',
// Silence unrelated noise for cleaner logs; Strapi's own logger is still active.
STRAPI_TELEMETRY_DISABLED: '1',
STRAPI_DISABLE_UPDATE_NOTIFIER: '1',
};
// Strapi configs in examples/complex are .ts — compile them to dist/ first
// (same path Strapi's own CLI uses via `strapi build` / `strapi develop`).
// Then boot Strapi pointing at the compiled output.
const script = `
const tsUtils = require('@strapi/typescript-utils');
const { createStrapi } = require('@strapi/strapi');
(async () => {
const cwd = process.cwd();
if (await tsUtils.isUsingTypeScript(cwd)) {
await tsUtils.compile(cwd, { configOptions: { ignoreDiagnostics: true } });
}
const distDir = await tsUtils.resolveOutDir(cwd);
const app = await createStrapi({ distDir }).load();
// Migrations ran during load(). Tear down cleanly.
await app.destroy();
})().catch((err) => {
console.error('[bench] strapi boot failed:', err);
process.exit(1);
});
`;
const hookPath = path.resolve(SCRIPT_DIR, 'bench-hook.js');
const start = performance.now();
const result = spawnSync('node', ['--require', hookPath, '-e', script], {
cwd: COMPLEX_DIR,
env,
stdio: 'inherit',
});
const wallMs = performance.now() - start;
if (result.status !== 0) {
console.error(`[bench] strapi boot exited with status ${result.status}`);
process.exit(result.status ?? 1);
}
return { wallMs };
}
// ─── subcommand: run ──────────────────────────────────────────────────────────
function cmdRun(args) {
const db = requireArg(args, 'db');
if (!SUPPORTED_DBS.includes(db)) {
console.error(`Error: --db must be one of: ${SUPPORTED_DBS.join(', ')}`);
process.exit(1);
}
const label = requireArg(args, 'label');
const snapshot = args.snapshot || `bench-m${args.multiplier || 1}`;
const multiplier = Number(args.multiplier ?? 1);
const strapiSource = args['strapi-source'] || 'local';
if (strapiSource !== 'local') {
console.error(
`Error: --strapi-source=${strapiSource} is not yet implemented. Use \`local\` and swap branches with \`git checkout\` / \`gh pr checkout\`.`
);
process.exit(1);
}
if (!snapshotExists(db, snapshot)) {
console.error(`Error: snapshot "${snapshot}" does not exist for ${db}.`);
console.error(`Run \`yarn bench:seed --db ${db} --multiplier ${multiplier}\` first.`);
process.exit(1);
}
// Ensure the results dir exists before the hook tries to write.
if (!fs.existsSync(RESULTS_DIR)) fs.mkdirSync(RESULTS_DIR, { recursive: true });
// Restore DB
restoreSnapshot(db, snapshot);
// Run migrations with timing hook
const hookOut = path.join(os.tmpdir(), `strapi-bench-hook-${process.pid}-${Date.now()}.json`);
console.log(`[bench] running migrations against ${db} (label=${label})...`);
const { wallMs } = runMigrationsOnce(db, hookOut);
// Ingest hook output
let hookData = { migrations: [], instanceCount: 0 };
if (fs.existsSync(hookOut)) {
try {
hookData = JSON.parse(fs.readFileSync(hookOut, 'utf8'));
} catch (err) {
console.error(`[bench] failed to parse hook output: ${err.message}`);
}
fs.unlinkSync(hookOut);
}
if (!hookData.migrations.length) {
console.warn(
'[bench] WARNING: hook captured zero migrations. Either Umzug API changed, or migrations were skipped as already-applied. Check the output below.'
);
}
const totalDurationMs = hookData.migrations.reduce((a, m) => a + m.durationMs, 0);
const rowCount = collectRowCounts(db);
const timestamp = new Date().toISOString();
const result = {
timestamp,
label,
...captureStrapiSource(),
strapiSource,
env: captureEnv(db),
config: {
multiplier,
snapshot,
seedMode: 'knex',
hookMode: 'prototype',
},
rowCount,
migrations: hookData.migrations,
totalDurationMs,
wallDurationMs: wallMs,
umzugInstanceCount: hookData.instanceCount,
};
const outFile = path.join(RESULTS_DIR, `${db}-${label}-${timestamp.replace(/[:.]/g, '-')}.json`);
fs.writeFileSync(outFile, JSON.stringify(result, null, 2), 'utf8');
console.log(`\n✅ Benchmark complete.`);
console.log(` DB: ${db}`);
console.log(` Label: ${label}`);
console.log(` Migrations: ${hookData.migrations.length}`);
console.log(` Total: ${totalDurationMs.toFixed(1)} ms (wall ${wallMs.toFixed(0)} ms)`);
console.log(` Result: ${path.relative(COMPLEX_DIR, outFile)}`);
}
// ─── subcommand: seed ─────────────────────────────────────────────────────────
function cmdSeed(args) {
const db = requireArg(args, 'db');
if (!SUPPORTED_DBS.includes(db)) {
console.error(`Error: --db must be one of: ${SUPPORTED_DBS.join(', ')}`);
process.exit(1);
}
const multiplier = Number(args.multiplier ?? 1);
const seedMode = args['seed-mode'] || 'strapi'; // knex mode is a follow-on
const snapshotName = `bench-m${multiplier}`;
if (seedMode !== 'strapi') {
console.error(
`Error: --seed-mode=${seedMode} is not yet implemented. Only \`strapi\` is available in the first iteration. The knex fast-seed path is tracked as a follow-up.`
);
process.exit(1);
}
if (!fs.existsSync(V4_PROJECT_DIR)) {
console.error(`Error: v4 project not found at ${V4_PROJECT_DIR}. Run \`yarn setup:v4\` first.`);
process.exit(1);
}
// Step 1: wipe DB (destructive; explicit per plan)
console.log(`[bench:seed] wiping ${db}...`);
execSync(`node ${path.join('scripts', `db-${db}.js`)} wipe`, {
cwd: COMPLEX_DIR,
stdio: 'inherit',
});
// Step 2: run v4 seed via the v4 project's seed-with-db wrapper.
// This boots Strapi v4, which creates the schema + bootstrap data, then runs seed.js.
console.log(`[bench:seed] seeding via Strapi v4 API (multiplier=${multiplier})...`);
execSync(`node scripts/seed-with-db.js ${db} ${multiplier}`, {
cwd: V4_PROJECT_DIR,
stdio: 'inherit',
});
// Step 3: snapshot
console.log(`[bench:seed] snapshotting as "${snapshotName}"...`);
execSync(`node ${path.join('scripts', `db-${db}.js`)} snapshot ${snapshotName}`, {
cwd: COMPLEX_DIR,
stdio: 'inherit',
});
console.log(`\n✅ Seed + snapshot ready: ${db}/${snapshotName}`);
console.log(` Run \`yarn bench:run --db ${db} --label <label>\` to benchmark.`);
}
// ─── subcommand: suite ────────────────────────────────────────────────────────
function cmdSuite(args) {
const multiplier = Number(args.multiplier ?? 1);
const baselineLabel = args.baseline || 'baseline';
const candidateLabel = args.candidate || 'candidate';
const dbs = (args.dbs || SUPPORTED_DBS.join(',')).split(',').filter(Boolean);
console.log(
`[bench:suite] running ${baselineLabel} + ${candidateLabel} across ${dbs.join(', ')} @ multiplier=${multiplier}`
);
console.log(
`[bench:suite] ASSUMPTION: you have already seeded each DB (\`yarn bench:seed --db <db> --multiplier ${multiplier}\`).`
);
console.log(
`[bench:suite] ASSUMPTION: you switch the monorepo checkout between baseline and candidate manually BEFORE invoking this.`
);
for (const db of dbs) {
if (!SUPPORTED_DBS.includes(db)) {
console.error(`[bench:suite] skipping unknown db: ${db}`);
continue;
}
console.log(`\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
console.log(`[bench:suite] ${db}: running under current strapi checkout...`);
console.log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`);
// The suite subcommand runs under whatever branch is checked out. The
// caller is responsible for sequencing baseline vs candidate runs.
const label = args.label || baselineLabel;
cmdRun({ db, label, multiplier, snapshot: `bench-m${multiplier}` });
}
}
// ─── main ─────────────────────────────────────────────────────────────────────
const subcommand = process.argv[2];
const rest = process.argv.slice(3);
const args = parseArgs(rest);
switch (subcommand) {
case 'run':
cmdRun(args);
break;
case 'seed':
cmdSeed(args);
break;
case 'suite':
cmdSuite(args);
break;
default:
console.error('Usage: node bench.js <run|seed|suite> [options]');
console.error('');
console.error(' run --db <db> --label <label> [--multiplier <n>] [--snapshot <name>]');
console.error(' seed --db <db> --multiplier <n> [--seed-mode strapi|knex]');
console.error(
' suite --multiplier <n> [--dbs postgres,mysql,mariadb,sqlite] [--label <tag>]'
);
process.exit(1);
}