feat(database-lab): add local database test environments
This commit is contained in:
@@ -0,0 +1,391 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
import { existsSync, readFileSync, readdirSync } from 'node:fs';
|
||||
import { basename, dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
|
||||
const REPO_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
export const DEFAULT_RECIPES_ROOT = join(REPO_ROOT, 'deploy', 'database');
|
||||
const DEFAULT_MAKEFILE_PATH = join(REPO_ROOT, 'Makefile');
|
||||
const DEFAULT_PASSWORD = '123456';
|
||||
const DEFAULT_DATABASE = 'dbx';
|
||||
|
||||
export function discoverRecipes(root = DEFAULT_RECIPES_ROOT) {
|
||||
if (!existsSync(root)) return [];
|
||||
const recipes = [];
|
||||
for (const database of readdirSync(root, { withFileTypes: true })) {
|
||||
if (!database.isDirectory()) continue;
|
||||
const databaseDir = join(root, database.name);
|
||||
for (const version of readdirSync(databaseDir, { withFileTypes: true })) {
|
||||
if (!version.isDirectory()) continue;
|
||||
const recipePath = join(databaseDir, version.name, 'recipe.json');
|
||||
if (!existsSync(recipePath)) continue;
|
||||
const recipe = JSON.parse(readFileSync(recipePath, 'utf8'));
|
||||
recipes.push({ ...recipe, directory: dirname(recipePath), recipePath });
|
||||
}
|
||||
}
|
||||
return recipes.sort((a, b) => `${a.database}/${a.displayVersion}`.localeCompare(`${b.database}/${b.displayVersion}`, 'en'));
|
||||
}
|
||||
|
||||
export function recipeSelector(recipe) {
|
||||
return `${recipe.database}@${recipe.displayVersion}`;
|
||||
}
|
||||
|
||||
export function discoverMakeTargets(makefilePath = DEFAULT_MAKEFILE_PATH) {
|
||||
if (!existsSync(makefilePath)) return [];
|
||||
const source = readFileSync(makefilePath, 'utf8').replace(/\\\r?\n/g, ' ');
|
||||
const targets = [];
|
||||
for (const line of source.split(/\r?\n/)) {
|
||||
const match = line.match(/^\.PHONY:\s*(.+)$/);
|
||||
if (match) targets.push(...match[1].trim().split(/\s+/));
|
||||
}
|
||||
return [...new Set(targets)];
|
||||
}
|
||||
|
||||
export function platformForArchitecture(architecture = process.arch) {
|
||||
if (architecture === 'x64') return 'linux/amd64';
|
||||
if (architecture === 'arm64') return 'linux/arm64';
|
||||
return null;
|
||||
}
|
||||
|
||||
export function architectureWarning(recipe, architecture = process.arch) {
|
||||
const platform = platformForArchitecture(architecture);
|
||||
if (!platform || recipe.platforms?.includes(platform)) return null;
|
||||
return `${recipe.image} does not support ${platform}. Docker must use ${recipe.platforms.join(', ')} emulation and startup may be slower.`;
|
||||
}
|
||||
|
||||
function printQuickStart(recipes) {
|
||||
console.log('Database test environments');
|
||||
console.log('Copy one command to start an environment:');
|
||||
console.log('');
|
||||
for (const recipe of recipes) console.log(` make db DB=${recipeSelector(recipe)}`);
|
||||
console.log('');
|
||||
console.log('Optional parameters:');
|
||||
console.log(' DB_BIND_ADDRESS=<ip> Override the default bind address (127.0.0.1).');
|
||||
console.log(' DB_PORT=<port> Override the default host port.');
|
||||
console.log(' DB_PASSWORD=<password> Override the default password (123456).');
|
||||
console.log('');
|
||||
console.log('Next steps: make db-verify DB=<product>@<version>, make db-down DB=<product>@<version>');
|
||||
console.log('Tab completion: make db-completion');
|
||||
}
|
||||
|
||||
function printCompletionSetup() {
|
||||
console.log('Bash: source deploy/database/completion/dbx-make.bash');
|
||||
console.log('Zsh: autoload -Uz compinit && compinit && source deploy/database/completion/_dbx-make.zsh');
|
||||
console.log('PowerShell: . .\\deploy\\database\\completion\\Dbx.Make.ps1');
|
||||
}
|
||||
|
||||
export function resolveRecipe(recipes, database, version) {
|
||||
if (!database) throw new Error('DB is required. Run `make db-list` to see available environments.');
|
||||
const matches = recipes.filter((item) => item.database === database && (!version || item.displayVersion === version || item.version === version));
|
||||
if (matches.length === 0) throw new Error(`No database environment found for ${database}${version ? ` ${version}` : ''}.`);
|
||||
if (matches.length > 1) throw new Error(`${database} has multiple versions (${matches.map((item) => item.displayVersion).join(', ')}). Use DB=${database}@<version> (or DB_VERSION).`);
|
||||
return matches[0];
|
||||
}
|
||||
|
||||
export function parseDatabaseSelection(selection, explicitVersion) {
|
||||
if (!selection) return { database: selection, version: explicitVersion };
|
||||
const selectorIndex = selection.lastIndexOf('@');
|
||||
if (selectorIndex === -1) return { database: selection, version: explicitVersion };
|
||||
|
||||
const database = selection.slice(0, selectorIndex);
|
||||
const selectorVersion = selection.slice(selectorIndex + 1);
|
||||
if (!database || !selectorVersion) throw new Error('DB must use the format <product>@<version>, for example DB=mysql@8.4.');
|
||||
if (explicitVersion && explicitVersion !== selectorVersion) {
|
||||
throw new Error(`DB version ${selectorVersion} conflicts with DB_VERSION=${explicitVersion}.`);
|
||||
}
|
||||
return { database, version: explicitVersion || selectorVersion };
|
||||
}
|
||||
|
||||
export function assertResetConfirmed(value) {
|
||||
if (value !== '1') throw new Error('Reset deletes the environment volume. Re-run with CONFIRM=1.');
|
||||
}
|
||||
|
||||
export function expectedContainerName(recipe) {
|
||||
return `dbx-${recipe.database}-${recipe.displayVersion}`.toLowerCase().replace(/[^a-z0-9_.-]+/g, '-');
|
||||
}
|
||||
|
||||
export function validateRecipe(recipe) {
|
||||
const errors = [];
|
||||
for (const field of ['database', 'version', 'displayVersion', 'service', 'connection', 'smoke', 'shell', 'defaultPort']) {
|
||||
if (recipe[field] === undefined) errors.push(`missing ${field}`);
|
||||
}
|
||||
if (!recipe.image || !/^[^\s]+:[^\s]+$/.test(recipe.image)) errors.push('image must be a pinned image reference');
|
||||
if (recipe.connection?.host !== '127.0.0.1') errors.push('connection.host must be 127.0.0.1');
|
||||
if (!Number.isInteger(recipe.defaultPort) || recipe.defaultPort < 1 || recipe.defaultPort > 65534) {
|
||||
errors.push('defaultPort must be an integer between 1 and 65534');
|
||||
} else if (recipe.connection?.port !== recipe.defaultPort + 1) {
|
||||
errors.push('connection.port must be defaultPort + 1');
|
||||
}
|
||||
if (recipe.connection?.password !== DEFAULT_PASSWORD) errors.push(`connection.password must be ${DEFAULT_PASSWORD}`);
|
||||
if (recipe.database === 'redis' ? recipe.connection?.database !== 0 : recipe.connection?.database !== DEFAULT_DATABASE) {
|
||||
errors.push(`connection.database must be ${recipe.database === 'redis' ? '0 for Redis' : DEFAULT_DATABASE}`);
|
||||
}
|
||||
if (!Array.isArray(recipe.platforms) || recipe.platforms.length === 0) errors.push('platforms must not be empty');
|
||||
else if (recipe.platforms.some((platform) => !['linux/amd64', 'linux/arm64'].includes(platform))) {
|
||||
errors.push('platforms contains an unsupported platform');
|
||||
}
|
||||
if (basename(recipe.directory) !== recipe.displayVersion || basename(dirname(recipe.directory)) !== recipe.database) {
|
||||
errors.push('recipe directory must match database/displayVersion');
|
||||
}
|
||||
const composePath = join(recipe.directory, 'compose.yaml');
|
||||
if (!existsSync(composePath)) errors.push('missing compose.yaml');
|
||||
else {
|
||||
const compose = readFileSync(composePath, 'utf8');
|
||||
if (!compose.includes(`container_name: ${expectedContainerName(recipe)}`)) {
|
||||
errors.push(`compose.yaml container_name must be ${expectedContainerName(recipe)}`);
|
||||
}
|
||||
if (/image:\s*[^\n]*:latest(?:\s|$)/.test(compose)) errors.push('compose.yaml must not use latest');
|
||||
if (!/healthcheck\s*:/.test(compose)) errors.push('compose.yaml must define a healthcheck');
|
||||
if (!/^volumes\s*:/m.test(compose)) errors.push('compose.yaml must define a named volume');
|
||||
if (!compose.includes(`image: ${recipe.image}`)) errors.push('compose.yaml image must match recipe.image');
|
||||
if (recipe.platforms?.length === 1 && !compose.includes(`platform: ${recipe.platforms[0]}`)) {
|
||||
errors.push(`single-platform image must set compose platform to ${recipe.platforms[0]}`);
|
||||
}
|
||||
if (!allPortMappingsDefaultToLoopback(compose)) {
|
||||
errors.push('compose.yaml ports must default every mapping to 127.0.0.1 via DB_BIND_ADDRESS');
|
||||
}
|
||||
if (!serviceHasNamedVolume(compose, recipe.service)) errors.push('target service must mount a named volume');
|
||||
if (!compose.includes(`\${DB_PORT:-${recipe.connection?.port}}:${recipe.defaultPort}`)) {
|
||||
errors.push('compose.yaml must default DB_PORT to connection.port and target defaultPort');
|
||||
}
|
||||
}
|
||||
const initDirectory = join(recipe.directory, 'init');
|
||||
if (!existsSync(initDirectory) || readdirSync(initDirectory).length === 0) errors.push('init directory must contain a file');
|
||||
if (!Array.isArray(recipe.smoke?.steps) || recipe.smoke.steps.length === 0) errors.push('smoke.steps must not be empty');
|
||||
for (const step of recipe.smoke?.steps ?? []) {
|
||||
if (!step.name || !Array.isArray(step.command) || step.command.length === 0) errors.push('every smoke step needs a name and command');
|
||||
if (typeof step.expect !== 'string' || step.expect.length === 0) errors.push('every smoke step needs an expected output');
|
||||
}
|
||||
if (!Array.isArray(recipe.shell) || recipe.shell.length === 0) errors.push('shell must be a non-empty command array');
|
||||
return errors;
|
||||
}
|
||||
|
||||
function indentation(line) {
|
||||
return line.length - line.trimStart().length;
|
||||
}
|
||||
|
||||
function serviceBlock(compose, service) {
|
||||
const lines = compose.split(/\r?\n/);
|
||||
const start = lines.findIndex((line) => new RegExp(`^\\s{2}${service.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}:\\s*$`).test(line));
|
||||
if (start === -1) return [];
|
||||
const block = [];
|
||||
for (let index = start + 1; index < lines.length; index += 1) {
|
||||
const line = lines[index];
|
||||
if (line.trim() && indentation(line) <= 2) break;
|
||||
block.push(line);
|
||||
}
|
||||
return block;
|
||||
}
|
||||
|
||||
export function allPortMappingsDefaultToLoopback(compose) {
|
||||
const lines = compose.split(/\r?\n/);
|
||||
let portsIndent = null;
|
||||
let foundMapping = false;
|
||||
for (const line of lines) {
|
||||
const trimmed = line.trim();
|
||||
const lineIndent = indentation(line);
|
||||
if (/^ports\s*:/.test(trimmed)) {
|
||||
portsIndent = lineIndent;
|
||||
const inlineMappings = trimmed.match(/['\"]([^'\"]+)['\"]/g) ?? [];
|
||||
if (inlineMappings.length > 0) {
|
||||
foundMapping = true;
|
||||
if (inlineMappings.some((mapping) => !mapping.slice(1, -1).startsWith('${DB_BIND_ADDRESS:-127.0.0.1}:'))) return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (portsIndent === null) continue;
|
||||
if (trimmed && lineIndent <= portsIndent) {
|
||||
portsIndent = null;
|
||||
continue;
|
||||
}
|
||||
if (!trimmed.startsWith('-')) continue;
|
||||
foundMapping = true;
|
||||
const mapping = trimmed.slice(1).trim().replace(/^['\"]|['\"]$/g, '');
|
||||
if (!mapping.startsWith('${DB_BIND_ADDRESS:-127.0.0.1}:')) return false;
|
||||
}
|
||||
return foundMapping;
|
||||
}
|
||||
|
||||
export function serviceHasNamedVolume(compose, service) {
|
||||
const block = serviceBlock(compose, service);
|
||||
let volumesIndent = null;
|
||||
for (const line of block) {
|
||||
const trimmed = line.trim();
|
||||
const lineIndent = indentation(line);
|
||||
if (/^volumes\s*:/.test(trimmed)) {
|
||||
volumesIndent = lineIndent;
|
||||
continue;
|
||||
}
|
||||
if (volumesIndent === null) continue;
|
||||
if (trimmed && lineIndent <= volumesIndent) {
|
||||
volumesIndent = null;
|
||||
continue;
|
||||
}
|
||||
if (!trimmed.startsWith('-')) continue;
|
||||
const mount = trimmed.slice(1).trim().replace(/^['\"]|['\"]$/g, '');
|
||||
if (/^[A-Za-z0-9][A-Za-z0-9_.-]*:/.test(mount) && !mount.startsWith('./') && !mount.startsWith('../')) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function composeArgs(recipe, ...args) {
|
||||
const project = (process.env.DB_PROJECT || `dbx-${basename(REPO_ROOT)}-${recipe.database}-${recipe.displayVersion}`).toLowerCase().replace(/[^a-z0-9_-]+/g, '-');
|
||||
return ['compose', '--project-name', project, '--file', join(recipe.directory, 'compose.yaml'), ...args];
|
||||
}
|
||||
|
||||
function run(command, args, options = {}) {
|
||||
const result = spawnSync(command, args, { cwd: options.cwd ?? REPO_ROOT, env: process.env, encoding: 'utf8', stdio: options.capture ? 'pipe' : 'inherit' });
|
||||
if (result.error) throw result.error;
|
||||
if (result.status !== 0) {
|
||||
const detail = options.capture ? `\n${result.stderr || result.stdout}` : '';
|
||||
throw new Error(`${command} ${args.join(' ')} failed with exit code ${result.status}.${detail}`);
|
||||
}
|
||||
return options.capture ? `${result.stdout ?? ''}${result.stderr ?? ''}` : '';
|
||||
}
|
||||
|
||||
function runCompose(recipe, args, options) {
|
||||
return run('docker', composeArgs(recipe, ...args), options);
|
||||
}
|
||||
|
||||
export function expandSmokeCommand(command, recipe, environment = process.env) {
|
||||
const values = {
|
||||
DB_PASSWORD: environment.DB_PASSWORD || recipe.connection.password,
|
||||
DB_PORT: environment.DB_PORT || String(recipe.connection.port),
|
||||
};
|
||||
return command.map((value) => value.replace(/\$\{(DB_PASSWORD|DB_PORT)\}/g, (_, name) => values[name]));
|
||||
}
|
||||
|
||||
function printConnection(recipe) {
|
||||
const connection = { ...recipe.connection };
|
||||
if (process.env.DB_PORT) connection.port = Number(process.env.DB_PORT);
|
||||
if (process.env.DB_PASSWORD) connection.password = process.env.DB_PASSWORD;
|
||||
console.log(`${recipe.name} (${recipe.version})`);
|
||||
for (const [key, value] of Object.entries(connection)) console.log(`${key}: ${value}`);
|
||||
if (recipe.notes) console.log(`notes: ${recipe.notes}`);
|
||||
const warning = architectureWarning(recipe);
|
||||
if (warning) console.warn(`warning: ${warning}`);
|
||||
}
|
||||
|
||||
function checkRecipes(recipes) {
|
||||
let failed = false;
|
||||
for (const recipe of recipes) {
|
||||
const errors = validateRecipe(recipe);
|
||||
if (errors.length) {
|
||||
failed = true;
|
||||
console.error(`FAIL ${recipe.database}/${recipe.displayVersion}: ${errors.join('; ')}`);
|
||||
continue;
|
||||
}
|
||||
const result = spawnSync('docker', composeArgs(recipe, 'config', '--format', 'json'), {
|
||||
encoding: 'utf8',
|
||||
env: { ...process.env, DB_BIND_ADDRESS: '' },
|
||||
});
|
||||
if (result.error?.code === 'ENOENT') {
|
||||
console.log(`OK ${recipe.database}/${recipe.displayVersion} (static checks; Docker unavailable)`);
|
||||
} else if (result.status !== 0) {
|
||||
failed = true;
|
||||
console.error(`FAIL ${recipe.database}/${recipe.displayVersion}: docker compose config failed\n${result.stderr}`);
|
||||
} else {
|
||||
try {
|
||||
validateRenderedCompose(recipe, JSON.parse(result.stdout));
|
||||
console.log(`OK ${recipe.database}/${recipe.displayVersion}`);
|
||||
} catch (error) {
|
||||
failed = true;
|
||||
console.error(`FAIL ${recipe.database}/${recipe.displayVersion}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (failed) throw new Error('Database environment checks failed.');
|
||||
}
|
||||
|
||||
export function validateRenderedCompose(recipe, rendered) {
|
||||
const service = rendered.services?.[recipe.service];
|
||||
if (!service) throw new Error('rendered Compose config is missing the target service');
|
||||
if (service.container_name !== expectedContainerName(recipe)) {
|
||||
throw new Error(`rendered target service container_name must be ${expectedContainerName(recipe)}`);
|
||||
}
|
||||
if (!service.healthcheck?.test) throw new Error('rendered target service is missing a healthcheck');
|
||||
const ports = service.ports ?? [];
|
||||
if (ports.length === 0 || ports.some((port) => typeof port !== 'object' || port.host_ip !== '127.0.0.1')) {
|
||||
throw new Error('rendered target service has a port mapping that does not default to 127.0.0.1');
|
||||
}
|
||||
const volumes = service.volumes ?? [];
|
||||
if (!volumes.some((volume) => typeof volume === 'object' && volume.type === 'volume')) {
|
||||
throw new Error('rendered target service does not mount a named volume');
|
||||
}
|
||||
}
|
||||
|
||||
export function main(argv = process.argv.slice(2)) {
|
||||
const [command = 'list', positionalDatabase, positionalVersion] = argv.filter((argument) => argument && argument !== '--');
|
||||
const recipes = discoverRecipes();
|
||||
|
||||
if (command === 'list') {
|
||||
console.log('DATABASE\tVERSION\tIMAGE\tPLATFORMS');
|
||||
for (const recipe of recipes) console.log(`${recipe.database}\t${recipe.displayVersion}\t${recipe.image}\t${recipe.platforms.join(',')}`);
|
||||
return;
|
||||
}
|
||||
if (command === 'quick-start') return printQuickStart(recipes);
|
||||
if (command === 'completion') return printCompletionSetup();
|
||||
if (command === 'selectors') {
|
||||
for (const recipe of recipes) console.log(recipeSelector(recipe));
|
||||
return;
|
||||
}
|
||||
if (command === 'make-targets') {
|
||||
for (const target of discoverMakeTargets()) console.log(target);
|
||||
return;
|
||||
}
|
||||
if (command === 'check') return checkRecipes(recipes);
|
||||
|
||||
const { database, version } = parseDatabaseSelection(process.env.DB || positionalDatabase, process.env.DB_VERSION || positionalVersion);
|
||||
|
||||
if (command === 'start' && !database) return printQuickStart(recipes);
|
||||
|
||||
const recipe = resolveRecipe(recipes, database, version);
|
||||
switch (command) {
|
||||
case 'info':
|
||||
printConnection(recipe);
|
||||
break;
|
||||
case 'start':
|
||||
case 'up':
|
||||
runCompose(recipe, ['up', '-d', '--wait']);
|
||||
printConnection(recipe);
|
||||
break;
|
||||
case 'status':
|
||||
runCompose(recipe, ['ps']);
|
||||
break;
|
||||
case 'logs':
|
||||
runCompose(recipe, process.env.FOLLOW === '1' ? ['logs', '--follow'] : ['logs']);
|
||||
break;
|
||||
case 'shell':
|
||||
runCompose(recipe, ['exec', recipe.service, ...expandSmokeCommand(recipe.shell, recipe)]);
|
||||
break;
|
||||
case 'verify':
|
||||
runCompose(recipe, ['up', '-d', '--wait']);
|
||||
for (const step of recipe.smoke.steps) {
|
||||
const command = expandSmokeCommand(step.command, recipe);
|
||||
const output = runCompose(recipe, ['exec', '-T', recipe.service, ...command], { capture: true });
|
||||
if (step.expect && !output.includes(step.expect)) throw new Error(`Smoke check did not contain expected text: ${step.expect}\n${output}`);
|
||||
console.log(`OK ${step.name}`);
|
||||
}
|
||||
break;
|
||||
case 'down':
|
||||
runCompose(recipe, ['down', '--remove-orphans']);
|
||||
break;
|
||||
case 'reset':
|
||||
assertResetConfirmed(process.env.CONFIRM);
|
||||
runCompose(recipe, ['down', '--volumes', '--remove-orphans']);
|
||||
break;
|
||||
default:
|
||||
throw new Error(`Unknown command: ${command}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (process.argv[1] && resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
try {
|
||||
main();
|
||||
} catch (error) {
|
||||
console.error(`Error: ${error.message}`);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { mkdtempSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import { DEFAULT_RECIPES_ROOT, allPortMappingsDefaultToLoopback, architectureWarning, assertResetConfirmed, discoverMakeTargets, discoverRecipes, expandSmokeCommand, expectedContainerName, parseDatabaseSelection, platformForArchitecture, recipeSelector, resolveRecipe, serviceHasNamedVolume, validateRecipe, validateRenderedCompose } from './database-env.mjs';
|
||||
|
||||
const bashAvailable = spawnSync('bash', ['--version'], { stdio: 'ignore' }).status === 0;
|
||||
const zshAvailable = spawnSync('zsh', ['--version'], { stdio: 'ignore' }).status === 0;
|
||||
const dockerComposeAvailable = spawnSync('docker', ['compose', 'version'], { stdio: 'ignore' }).status === 0;
|
||||
|
||||
function fixture(database, version) {
|
||||
const root = mkdtempSync(join(tmpdir(), 'dbx-db-env-'));
|
||||
const directory = join(root, database, version);
|
||||
mkdirSync(join(directory, 'init'), { recursive: true });
|
||||
writeFileSync(join(directory, 'init', '001-smoke.txt'), 'fixture initialization');
|
||||
writeFileSync(join(directory, 'recipe.json'), JSON.stringify({ database, version, displayVersion: version, name: database, image: 'test:1', platforms: ['linux/amd64'], service: 'database', defaultPort: 1234, connection: { host: '127.0.0.1', port: 1235, password: '123456', database: database === 'redis' ? 0 : 'dbx' }, smoke: { steps: [{ name: 'smoke', command: ['true'], expect: 'true' }] }, shell: ['true'] }));
|
||||
writeFileSync(join(directory, 'compose.yaml'), `services:\n database:\n image: test:1\n platform: linux/amd64\n container_name: dbx-${database}-${version}\n ports:\n - "\${DB_BIND_ADDRESS:-127.0.0.1}:\${DB_PORT:-1235}:1234"\n volumes:\n - data:/var/lib/database\n healthcheck:\n test: ["CMD", "true"]\nvolumes:\n data:\n`);
|
||||
return root;
|
||||
}
|
||||
|
||||
test('discovers versioned recipes', () => {
|
||||
const recipes = discoverRecipes(fixture('mysql', '5.7'));
|
||||
assert.equal(recipes.length, 1);
|
||||
assert.equal(recipes[0].database, 'mysql');
|
||||
});
|
||||
|
||||
test('requires DB and rejects ambiguous versions', () => {
|
||||
assert.throws(() => resolveRecipe([], ''), /DB is required/);
|
||||
const recipes = [{ database: 'mysql', displayVersion: '5.7' }, { database: 'mysql', displayVersion: '8.4' }];
|
||||
assert.throws(() => resolveRecipe(recipes, 'mysql'), /multiple versions/);
|
||||
assert.equal(resolveRecipe(recipes, 'mysql', '8.4').displayVersion, '8.4');
|
||||
});
|
||||
|
||||
test('accepts the compact product@version database selector', () => {
|
||||
assert.deepEqual(parseDatabaseSelection('mysql@8.4'), { database: 'mysql', version: '8.4' });
|
||||
assert.deepEqual(parseDatabaseSelection('mysql@8.4', '8.4'), { database: 'mysql', version: '8.4' });
|
||||
assert.throws(() => parseDatabaseSelection('mysql@8.4', '5.7'), /conflicts/);
|
||||
assert.throws(() => parseDatabaseSelection('mysql@'), /format/);
|
||||
});
|
||||
|
||||
test('formats a recipe as a copyable compact selector', () => {
|
||||
assert.equal(recipeSelector({ database: 'mysql', displayVersion: '8.4' }), 'mysql@8.4');
|
||||
});
|
||||
|
||||
test('discovers all public Make targets for shell completion', () => {
|
||||
const targets = discoverMakeTargets();
|
||||
for (const target of ['help', 'build', 'test', 'docs', 'db', 'db-verify', 'db-completion']) {
|
||||
assert.ok(targets.includes(target), `missing Make target: ${target}`);
|
||||
}
|
||||
assert.equal(new Set(targets).size, targets.length);
|
||||
});
|
||||
|
||||
test('Bash completion preserves all Make targets and completes database selectors', { skip: !bashAvailable }, () => {
|
||||
const repoRoot = join(DEFAULT_RECIPES_ROOT, '..', '..');
|
||||
const completionScript = join(DEFAULT_RECIPES_ROOT, 'completion', 'dbx-make.bash');
|
||||
const result = spawnSync(
|
||||
'bash',
|
||||
[
|
||||
'--noprofile',
|
||||
'--norc',
|
||||
'-c',
|
||||
'source "$COMPLETION_SCRIPT"; COMP_WORDS=(make ""); COMP_CWORD=1; _dbx_make; printf "TARGET:%s\\n" "${COMPREPLY[@]}"; COMP_WORDS=(make db DB=); COMP_CWORD=2; _dbx_make; printf "SELECTOR:%s\\n" "${COMPREPLY[@]}"',
|
||||
],
|
||||
{ cwd: repoRoot, env: { ...process.env, COMPLETION_SCRIPT: completionScript }, encoding: 'utf8' },
|
||||
);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /^TARGET:build$/m);
|
||||
assert.match(result.stdout, /^TARGET:test$/m);
|
||||
assert.match(result.stdout, /^TARGET:db$/m);
|
||||
assert.match(result.stdout, /^SELECTOR:DB=mysql@8\.4$/m);
|
||||
});
|
||||
|
||||
test('Bash completion delegates to the previous completer outside the repository', { skip: !bashAvailable }, () => {
|
||||
const completionScript = join(DEFAULT_RECIPES_ROOT, 'completion', 'dbx-make.bash');
|
||||
const result = spawnSync(
|
||||
'bash',
|
||||
[
|
||||
'--noprofile',
|
||||
'--norc',
|
||||
'-c',
|
||||
'_original_make_completion() { COMPREPLY=(ORIGINAL); }; complete -F _original_make_completion make; source "$COMPLETION_SCRIPT"; cd "$TMPDIR"; COMP_WORDS=(make db DB=); COMP_CWORD=2; _dbx_make; printf "%s\\n" "${COMPREPLY[@]}"',
|
||||
],
|
||||
{ env: { ...process.env, COMPLETION_SCRIPT: completionScript, TMPDIR: tmpdir() }, encoding: 'utf8' },
|
||||
);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.stdout.trim(), 'ORIGINAL');
|
||||
});
|
||||
|
||||
test('Zsh completion delegates ordinary Make completion and handles DB selectors', { skip: !zshAvailable }, () => {
|
||||
const repoRoot = join(DEFAULT_RECIPES_ROOT, '..', '..');
|
||||
const completionScript = join(DEFAULT_RECIPES_ROOT, 'completion', '_dbx-make.zsh');
|
||||
const result = spawnSync(
|
||||
'zsh',
|
||||
[
|
||||
'-f',
|
||||
'-c',
|
||||
'autoload -Uz compinit && compinit -D; _original_make_completion() { print ORIGINAL; }; compdef _original_make_completion make; source "$COMPLETION_SCRIPT"; words=(make ""); CURRENT=2; _dbx_make; _describe() { local values_name="$2"; print -l -- "${(@P)values_name}"; }; compset() { return 0; }; words=(make db DB=); CURRENT=3; _dbx_make',
|
||||
],
|
||||
{ cwd: repoRoot, env: { ...process.env, COMPLETION_SCRIPT: completionScript }, encoding: 'utf8' },
|
||||
);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /^ORIGINAL$/m);
|
||||
assert.match(result.stdout, /^mysql@8\.4$/m);
|
||||
});
|
||||
|
||||
test('records the MySQL 5.7 CNB mirror as a multi-architecture image', () => {
|
||||
const recipe = discoverRecipes().find((item) => recipeSelector(item) === 'mysql@5.7');
|
||||
assert.ok(recipe);
|
||||
assert.deepEqual(recipe.platforms, ['linux/amd64', 'linux/arm64']);
|
||||
assert.equal(recipe.notes, undefined);
|
||||
});
|
||||
|
||||
test('warns only when the current architecture is unsupported', () => {
|
||||
const recipe = { image: 'mirror/redis:3', platforms: ['linux/amd64'] };
|
||||
assert.equal(platformForArchitecture('arm64'), 'linux/arm64');
|
||||
assert.equal(architectureWarning(recipe, 'x64'), null);
|
||||
assert.match(architectureWarning(recipe, 'arm64'), /does not support linux\/arm64/);
|
||||
});
|
||||
|
||||
test('uses the approved CNB mirror images and matching recipe versions', () => {
|
||||
const recipes = Object.fromEntries(
|
||||
discoverRecipes().map((recipe) => [recipeSelector(recipe), { version: recipe.version, image: recipe.image, platforms: recipe.platforms }]),
|
||||
);
|
||||
assert.deepEqual(recipes, {
|
||||
'clickhouse@24.8': { version: '24.8.14.39', image: 'docker.cnb.cool/znb/images/clickhouse-server:24.8.14.39', platforms: ['linux/amd64', 'linux/arm64'] },
|
||||
'mariadb@10.11': { version: '10.11.11', image: 'docker.cnb.cool/znb/images/mariadb:10.11.11', platforms: ['linux/amd64', 'linux/arm64'] },
|
||||
'mongodb@5.0': { version: '5.0.5', image: 'docker.cnb.cool/znb/images/mongo:5.0.5', platforms: ['linux/amd64', 'linux/arm64'] },
|
||||
'mongodb@8.2': { version: '8.2.3', image: 'docker.cnb.cool/znb/images/mongo:8.2.3-noble', platforms: ['linux/amd64', 'linux/arm64'] },
|
||||
'mysql@5.7': { version: '5.7.44', image: 'docker.cnb.cool/znb/images/mysql:5.7.44', platforms: ['linux/amd64', 'linux/arm64'] },
|
||||
'mysql@8.4': { version: '8.4.6', image: 'docker.cnb.cool/znb/images/mysql:8.4.6', platforms: ['linux/amd64', 'linux/arm64'] },
|
||||
'postgresql@14.23': { version: '14.23', image: 'docker.cnb.cool/znb/images/postgres:14.23', platforms: ['linux/amd64', 'linux/arm64'] },
|
||||
'postgresql@17.4': { version: '17.4', image: 'docker.cnb.cool/znb/images/postgres:17.4', platforms: ['linux/amd64', 'linux/arm64'] },
|
||||
'redis@3.0.7': { version: '3.0.7', image: 'docker.cnb.cool/znb/images/redis:3.0.7-alpine', platforms: ['linux/amd64'] },
|
||||
'redis@7.4': { version: '7.4.9', image: 'docker.cnb.cool/znb/images/redis:7.4.9-alpine', platforms: ['linux/amd64', 'linux/arm64'] },
|
||||
});
|
||||
assert.equal(discoverRecipes().find((recipe) => recipeSelector(recipe) === 'redis@3.0.7').connection.username, undefined);
|
||||
});
|
||||
|
||||
test('start without DB prints every copyable database command', () => {
|
||||
const repoRoot = join(DEFAULT_RECIPES_ROOT, '..', '..');
|
||||
const result = spawnSync(process.execPath, ['scripts/database-env.mjs', 'start'], {
|
||||
cwd: repoRoot,
|
||||
env: { ...process.env, DB: '', DB_VERSION: '' },
|
||||
encoding: 'utf8',
|
||||
});
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
for (const recipe of discoverRecipes()) {
|
||||
assert.ok(result.stdout.includes(`make db DB=${recipeSelector(recipe)}`));
|
||||
}
|
||||
});
|
||||
|
||||
test('reset requires explicit confirmation', () => {
|
||||
assert.throws(() => assertResetConfirmed(''), /CONFIRM=1/);
|
||||
assert.doesNotThrow(() => assertResetConfirmed('1'));
|
||||
});
|
||||
|
||||
test('static validation accepts a minimal safe recipe', () => {
|
||||
const [recipe] = discoverRecipes(fixture('redis', '7.4'));
|
||||
assert.deepEqual(validateRecipe(recipe), []);
|
||||
});
|
||||
|
||||
test('smoke commands use password and port overrides without invoking a shell', () => {
|
||||
const recipe = { connection: { password: 'default-password', port: 3306 } };
|
||||
assert.deepEqual(
|
||||
expandSmokeCommand(['client', '--password=${DB_PASSWORD}', '--port=${DB_PORT}'], recipe, { DB_PASSWORD: 'override', DB_PORT: '13306' }),
|
||||
['client', '--password=override', '--port=13306'],
|
||||
);
|
||||
});
|
||||
|
||||
test('MongoDB commands pass reserved-character passwords as a distinct argument', () => {
|
||||
const password = 'p@ss/word#with?reserved&characters';
|
||||
for (const recipe of discoverRecipes().filter((item) => item.database === 'mongodb')) {
|
||||
for (const command of [recipe.shell, ...recipe.smoke.steps.map((step) => step.command)]) {
|
||||
const expanded = expandSmokeCommand(command, recipe, { DB_PASSWORD: password });
|
||||
const passwordIndex = expanded.indexOf('--password');
|
||||
assert.notEqual(passwordIndex, -1);
|
||||
assert.equal(expanded[passwordIndex + 1], password);
|
||||
assert.equal(expanded.some((argument) => argument.includes('mongodb://')), false);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('requires every port mapping to default to loopback with an explicit override', () => {
|
||||
assert.equal(allPortMappingsDefaultToLoopback('services:\n database:\n ports:\n - "127.0.0.1:3306:3306"'), false);
|
||||
assert.equal(allPortMappingsDefaultToLoopback('services:\n database:\n ports:\n - "${DB_BIND_ADDRESS:-127.0.0.1}:3306:3306"'), true);
|
||||
assert.equal(allPortMappingsDefaultToLoopback('services:\n database:\n ports:\n - "${DB_BIND_ADDRESS:-0.0.0.0}:3306:3306"'), false);
|
||||
});
|
||||
|
||||
test('rendered Compose recipes bind to loopback by default', { skip: !dockerComposeAvailable }, () => {
|
||||
const recipes = discoverRecipes();
|
||||
for (const recipe of recipes) {
|
||||
const result = spawnSync('docker', ['compose', '--file', join(recipe.directory, 'compose.yaml'), 'config', '--format', 'json'], {
|
||||
encoding: 'utf8',
|
||||
env: { ...process.env, DB_BIND_ADDRESS: '' },
|
||||
});
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.doesNotThrow(() => validateRenderedCompose(recipe, JSON.parse(result.stdout)));
|
||||
}
|
||||
|
||||
const remoteResult = spawnSync('docker', ['compose', '--file', join(recipes[0].directory, 'compose.yaml'), 'config', '--format', 'json'], {
|
||||
encoding: 'utf8',
|
||||
env: { ...process.env, DB_BIND_ADDRESS: '0.0.0.0' },
|
||||
});
|
||||
assert.equal(remoteResult.status, 0, remoteResult.stderr);
|
||||
const remoteService = JSON.parse(remoteResult.stdout).services[recipes[0].service];
|
||||
assert.ok(remoteService.ports.every((port) => port.host_ip === '0.0.0.0'));
|
||||
});
|
||||
|
||||
test('healthchecks safely reference configurable passwords', { skip: !dockerComposeAvailable }, () => {
|
||||
const password = "space ' password";
|
||||
const recipes = discoverRecipes().filter((recipe) => ['mariadb', 'mongodb', 'mysql', 'redis'].includes(recipe.database));
|
||||
|
||||
for (const recipe of recipes) {
|
||||
const result = spawnSync('docker', ['compose', '--file', join(recipe.directory, 'compose.yaml'), 'config', '--format', 'json'], {
|
||||
encoding: 'utf8',
|
||||
env: { ...process.env, DB_PASSWORD: password },
|
||||
});
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
|
||||
const service = JSON.parse(result.stdout).services[recipe.service];
|
||||
const command = service.healthcheck.test[1];
|
||||
assert.equal(command.includes(password), false, `${recipeSelector(recipe)} interpolates the password into CMD-SHELL`);
|
||||
|
||||
if (recipe.database === 'mongodb') assert.match(command, /--password "\$\$MONGO_INITDB_ROOT_PASSWORD"/);
|
||||
if (recipe.database === 'mysql') assert.match(command, /-p"\$\$MYSQL_ROOT_PASSWORD"/);
|
||||
if (recipe.database === 'mariadb') assert.match(command, /-p"\$\$MARIADB_ROOT_PASSWORD"/);
|
||||
if (recipe.database === 'redis') {
|
||||
assert.equal(service.environment.REDIS_PASSWORD, password);
|
||||
assert.match(command, /-a "\$\$REDIS_PASSWORD"/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('requires the target service to mount a named volume', () => {
|
||||
const bindOnly = 'services:\n database:\n volumes:\n - ./init:/docker-entrypoint-initdb.d:ro\nvolumes:\n data:\n';
|
||||
const namedVolume = 'services:\n database:\n volumes:\n - data:/var/lib/database\nvolumes:\n data:\n';
|
||||
assert.equal(serviceHasNamedVolume(bindOnly, 'database'), false);
|
||||
assert.equal(serviceHasNamedVolume(namedVolume, 'database'), true);
|
||||
});
|
||||
|
||||
test('derives the required dbx-prefixed container name', () => {
|
||||
assert.equal(expectedContainerName({ database: 'mysql', displayVersion: '5.7' }), 'dbx-mysql-5.7');
|
||||
assert.equal(expectedContainerName({ database: 'PostgreSQL', displayVersion: '17.4' }), 'dbx-postgresql-17.4');
|
||||
});
|
||||
|
||||
test('rejects a recipe whose Compose container name is not standardized', () => {
|
||||
const [recipe] = discoverRecipes(fixture('mysql', '8.4'));
|
||||
const composePath = join(recipe.directory, 'compose.yaml');
|
||||
writeFileSync(composePath, readFileSync(composePath, 'utf8').replace('container_name: dbx-mysql-8.4', 'container_name: custom-mysql'));
|
||||
assert.match(validateRecipe(recipe).join('; '), /container_name must be dbx-mysql-8.4/);
|
||||
});
|
||||
|
||||
test('requires the shared default password and database name', () => {
|
||||
const [recipe] = discoverRecipes(fixture('postgresql', '17.4'));
|
||||
recipe.connection.password = 'different';
|
||||
recipe.connection.database = 'other';
|
||||
assert.match(validateRecipe(recipe).join('; '), /connection.password must be 123456/);
|
||||
assert.match(validateRecipe(recipe).join('; '), /connection.database must be dbx/);
|
||||
});
|
||||
|
||||
test('requires every recipe port to be one greater than its database default port', () => {
|
||||
const [recipe] = discoverRecipes(fixture('postgresql', '17.4'));
|
||||
recipe.connection.port = 5432;
|
||||
assert.match(validateRecipe(recipe).join('; '), /connection.port must be defaultPort \+ 1/);
|
||||
});
|
||||
|
||||
test('reports missing smoke structures without throwing a TypeError', () => {
|
||||
const [recipe] = discoverRecipes(fixture('postgresql', '17.4'));
|
||||
delete recipe.smoke;
|
||||
let errors;
|
||||
assert.doesNotThrow(() => {
|
||||
errors = validateRecipe(recipe);
|
||||
});
|
||||
assert.match(errors.join('; '), /missing smoke/);
|
||||
assert.match(errors.join('; '), /smoke\.steps must not be empty/);
|
||||
|
||||
recipe.smoke = {};
|
||||
assert.doesNotThrow(() => validateRecipe(recipe));
|
||||
assert.match(validateRecipe(recipe).join('; '), /smoke\.steps must not be empty/);
|
||||
});
|
||||
|
||||
test('documents every checked-in recipe on both website pages', () => {
|
||||
const pages = [
|
||||
join(DEFAULT_RECIPES_ROOT, '..', '..', 'docs', 'content', 'docs', 'database-lab.mdx'),
|
||||
join(DEFAULT_RECIPES_ROOT, '..', '..', 'docs', 'content', 'docs', 'database-lab.cn.mdx'),
|
||||
].map((path) => readFileSync(path, 'utf8'));
|
||||
|
||||
for (const recipe of discoverRecipes()) {
|
||||
const entry = `\`${recipe.database}/${recipe.displayVersion}\``;
|
||||
for (const page of pages) assert.ok(page.includes(entry), `missing ${entry} from database lab documentation`);
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user