398 lines
15 KiB
TypeScript
398 lines
15 KiB
TypeScript
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
import { tmpdir } from 'node:os';
|
|
import { join } from 'node:path';
|
|
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
import { describe, expect, test } from 'bun:test';
|
|
import { stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config';
|
|
import { parseDbMigrateArgs, resolveMigrationTarget } from '../db-migrate';
|
|
|
|
const root = fileURLToPath(new URL('../../', import.meta.url));
|
|
const dbMigrateModuleUrl = pathToFileURL(join(root, 'scripts/db-migrate.ts')).href;
|
|
|
|
function makeConfig(overrides: {
|
|
environment?: StockAppConfig['environment'];
|
|
postgres?: Partial<StockAppConfig['database']['postgres']>;
|
|
}): StockAppConfig {
|
|
return stockAppSchema.parse({
|
|
name: 'stock-bot',
|
|
version: '1.0.0',
|
|
environment: overrides.environment ?? 'development',
|
|
service: {
|
|
name: 'data-pipeline',
|
|
port: 2002,
|
|
},
|
|
log: {},
|
|
database: {
|
|
postgres: {
|
|
enabled: true,
|
|
host: 'localhost',
|
|
port: 5433,
|
|
database: 'trading_bot_dev',
|
|
user: 'dev_user',
|
|
password: 'dev_pass',
|
|
ssl: false,
|
|
poolSize: 10,
|
|
connectionTimeout: 30000,
|
|
idleTimeout: 10000,
|
|
...overrides.postgres,
|
|
},
|
|
mongodb: {
|
|
enabled: true,
|
|
uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin',
|
|
database: 'stock_dev',
|
|
poolSize: 10,
|
|
},
|
|
questdb: {},
|
|
dragonfly: {},
|
|
},
|
|
providers: {},
|
|
features: {},
|
|
});
|
|
}
|
|
|
|
describe('parseDbMigrateArgs', () => {
|
|
test('defaults to track "all" when no arguments are passed', () => {
|
|
expect(parseDbMigrateArgs([])).toEqual({ track: 'all' });
|
|
});
|
|
|
|
test('accepts each valid track with space or equals syntax', () => {
|
|
for (const track of ['master', 'research', 'all'] as const) {
|
|
expect(parseDbMigrateArgs(['--track', track])).toEqual({ track });
|
|
expect(parseDbMigrateArgs([`--track=${track}`])).toEqual({ track });
|
|
}
|
|
});
|
|
|
|
test('rejects invalid track values with message listing valid tracks', () => {
|
|
expect(() => parseDbMigrateArgs(['--track', 'bogus'])).toThrow(/master\|research\|all/);
|
|
expect(() => parseDbMigrateArgs(['--track=bogus'])).toThrow(/master\|research\|all/);
|
|
});
|
|
|
|
test('rejects missing track value and unknown arguments', () => {
|
|
expect(() => parseDbMigrateArgs(['--track'])).toThrow(/master\|research\|all/);
|
|
expect(() => parseDbMigrateArgs(['--track', '--other'])).toThrow(/master\|research\|all/);
|
|
expect(() => parseDbMigrateArgs(['--unknown'])).toThrow(/master\|research\|all/);
|
|
expect(() => parseDbMigrateArgs(['positional'])).toThrow(/master\|research\|all/);
|
|
});
|
|
});
|
|
|
|
describe('resolveMigrationTarget', () => {
|
|
test('rejects development targeting QA PostgreSQL on localhost:5432/trading_bot', () => {
|
|
const config = makeConfig({
|
|
environment: 'development',
|
|
postgres: { host: 'localhost', port: 5432, database: 'trading_bot' },
|
|
});
|
|
expect(() => resolveMigrationTarget(config, {})).toThrow(/QA PostgreSQL/i);
|
|
});
|
|
|
|
test('rejects development targeting QA PostgreSQL on 127.0.0.1:5432/trading_bot', () => {
|
|
const config = makeConfig({
|
|
environment: 'development',
|
|
postgres: { host: '127.0.0.1', port: 5432, database: 'trading_bot' },
|
|
});
|
|
expect(() => resolveMigrationTarget(config, {})).toThrow(/QA PostgreSQL/i);
|
|
});
|
|
|
|
test('accepts development targeting isolated dev PostgreSQL on localhost:5433/trading_bot_dev', () => {
|
|
const config = makeConfig({
|
|
environment: 'development',
|
|
postgres: {
|
|
host: 'localhost',
|
|
port: 5433,
|
|
database: 'trading_bot_dev',
|
|
user: 'dev_user',
|
|
password: 'dev_pass',
|
|
},
|
|
});
|
|
const resolved = resolveMigrationTarget(config, {});
|
|
expect(resolved.targetLabel).toBe('localhost:5433/trading_bot_dev');
|
|
expect(resolved.clientConfig).toEqual({
|
|
host: 'localhost',
|
|
port: 5433,
|
|
database: 'trading_bot_dev',
|
|
username: 'dev_user',
|
|
password: 'dev_pass',
|
|
ssl: { enabled: false, rejectUnauthorized: true },
|
|
poolSettings: { min: 0, max: 10, idleTimeoutMillis: 10000 },
|
|
timeouts: { connection: 30000 },
|
|
});
|
|
});
|
|
|
|
test('rejects qa targeting a _dev database', () => {
|
|
const config = makeConfig({
|
|
environment: 'qa',
|
|
postgres: { host: 'localhost', port: 5433, database: 'trading_bot_dev' },
|
|
});
|
|
expect(() => resolveMigrationTarget(config, {})).toThrow(/dev PostgreSQL/i);
|
|
});
|
|
|
|
test('rejects development targeting QA PostgreSQL even when STOCK_BOT_ALLOW_DEV_ON_QA_DB=true', () => {
|
|
const config = makeConfig({
|
|
environment: 'development',
|
|
postgres: { host: 'localhost', port: 5432, database: 'trading_bot' },
|
|
});
|
|
expect(() =>
|
|
resolveMigrationTarget(config, { STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true' })
|
|
).toThrow(/QA PostgreSQL/i);
|
|
});
|
|
|
|
test('rejects disabled PostgreSQL configuration', () => {
|
|
const config = makeConfig({
|
|
environment: 'development',
|
|
postgres: { enabled: false },
|
|
});
|
|
expect(() => resolveMigrationTarget(config, {})).toThrow(/disabled/i);
|
|
});
|
|
});
|
|
|
|
function runInitInIsolatedSubprocess(
|
|
env: Record<string, string>,
|
|
mode: 'load-and-resolve' | 'load-only' = 'load-and-resolve'
|
|
): { exitCode: number; stdout: string; stderr: string } {
|
|
const isolatedDir = mkdtempSync(join(tmpdir(), 'stock-bot-db-migrate-env-'));
|
|
// Stop the config loader's upward .env search inside the temp directory.
|
|
writeFileSync(join(isolatedDir, '.env'), '', 'utf8');
|
|
const script =
|
|
mode === 'load-only'
|
|
? `import { loadMigrationConfig } from ${JSON.stringify(dbMigrateModuleUrl)};
|
|
const config = loadMigrationConfig();
|
|
console.log(JSON.stringify({ mongoEnabled: config.database.mongodb.enabled }));`
|
|
: `import { loadMigrationConfig, resolveMigrationTarget } from ${JSON.stringify(dbMigrateModuleUrl)};
|
|
const config = loadMigrationConfig();
|
|
const resolved = resolveMigrationTarget(config, process.env);
|
|
console.log(JSON.stringify({ mongoEnabled: config.database.mongodb.enabled, targetLabel: resolved.targetLabel }));`;
|
|
|
|
try {
|
|
const result = Bun.spawnSync([process.execPath, '-e', script], {
|
|
cwd: isolatedDir,
|
|
env: {
|
|
PATH: process.env.PATH ?? '',
|
|
HOME: isolatedDir,
|
|
...env,
|
|
},
|
|
});
|
|
return {
|
|
exitCode: result.exitCode,
|
|
stdout: new TextDecoder().decode(result.stdout).trim(),
|
|
stderr: new TextDecoder().decode(result.stderr).trim(),
|
|
};
|
|
} finally {
|
|
rmSync(isolatedDir, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
describe('loadMigrationConfig (real initialization path, isolated subprocess)', () => {
|
|
test('succeeds for dev PostgreSQL even when QA MongoDB admin URI is set without MONGODB_READ_URI', () => {
|
|
const result = runInitInIsolatedSubprocess({
|
|
NODE_ENV: 'development',
|
|
POSTGRES_HOST: 'localhost',
|
|
POSTGRES_PORT: '5433',
|
|
POSTGRES_DATABASE: 'trading_bot_dev',
|
|
POSTGRES_USERNAME: 'dev_user',
|
|
POSTGRES_PASSWORD: 'dev_pass',
|
|
DATABASE_POSTGRES_HOST: 'localhost',
|
|
DATABASE_POSTGRES_PORT: '5433',
|
|
DATABASE_POSTGRES_DATABASE: 'trading_bot_dev',
|
|
MONGODB_URI: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin',
|
|
});
|
|
|
|
expect(result.exitCode).toBe(0);
|
|
expect(JSON.parse(result.stdout)).toEqual({
|
|
mongoEnabled: false,
|
|
targetLabel: 'localhost:5433/trading_bot_dev',
|
|
});
|
|
});
|
|
|
|
test('rejects development targeting QA PostgreSQL during real config initialization', () => {
|
|
const result = runInitInIsolatedSubprocess(
|
|
{
|
|
NODE_ENV: 'development',
|
|
POSTGRES_HOST: 'localhost',
|
|
POSTGRES_PORT: '5432',
|
|
POSTGRES_DATABASE: 'trading_bot',
|
|
DATABASE_POSTGRES_HOST: 'localhost',
|
|
DATABASE_POSTGRES_PORT: '5432',
|
|
DATABASE_POSTGRES_DATABASE: 'trading_bot',
|
|
},
|
|
'load-only'
|
|
);
|
|
|
|
expect(result.exitCode).not.toBe(0);
|
|
expect(result.stderr).toMatch(/QA PostgreSQL/i);
|
|
});
|
|
|
|
test('rejects development targeting QA PostgreSQL even when STOCK_BOT_ALLOW_DEV_ON_QA_DB=true in real env', () => {
|
|
const result = runInitInIsolatedSubprocess({
|
|
NODE_ENV: 'development',
|
|
POSTGRES_HOST: 'localhost',
|
|
POSTGRES_PORT: '5432',
|
|
POSTGRES_DATABASE: 'trading_bot',
|
|
DATABASE_POSTGRES_HOST: 'localhost',
|
|
DATABASE_POSTGRES_PORT: '5432',
|
|
DATABASE_POSTGRES_DATABASE: 'trading_bot',
|
|
STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true',
|
|
});
|
|
|
|
expect(result.exitCode).not.toBe(0);
|
|
expect(result.stderr).toMatch(/QA PostgreSQL/i);
|
|
});
|
|
|
|
test('succeeds in production with unused MongoDB placeholder credential while still rejecting dev Postgres password', () => {
|
|
const okResult = runInitInIsolatedSubprocess({
|
|
NODE_ENV: 'production',
|
|
POSTGRES_HOST: 'pg.prod.internal',
|
|
POSTGRES_PORT: '5432',
|
|
POSTGRES_DATABASE: 'trading_bot',
|
|
POSTGRES_USERNAME: 'prod_user',
|
|
POSTGRES_PASSWORD: 'strong_prod_pg_secret_987',
|
|
DATABASE_POSTGRES_HOST: 'pg.prod.internal',
|
|
DATABASE_POSTGRES_PORT: '5432',
|
|
DATABASE_POSTGRES_DATABASE: 'trading_bot',
|
|
DATABASE_POSTGRES_PASSWORD: 'strong_prod_pg_secret_987',
|
|
MONGODB_URI: 'mongodb://prod:trading_mongo_dev@mongo.internal:27017/stock?authSource=admin',
|
|
DRAGONFLY_PASSWORD: 'strong_prod_redis_secret_987',
|
|
});
|
|
|
|
expect(okResult.exitCode).toBe(0);
|
|
expect(JSON.parse(okResult.stdout)).toEqual({
|
|
mongoEnabled: false,
|
|
targetLabel: 'pg.prod.internal:5432/trading_bot',
|
|
});
|
|
|
|
const badPgResult = runInitInIsolatedSubprocess({
|
|
NODE_ENV: 'production',
|
|
POSTGRES_HOST: 'pg.prod.internal',
|
|
POSTGRES_PORT: '5432',
|
|
POSTGRES_DATABASE: 'trading_bot',
|
|
POSTGRES_USERNAME: 'prod_user',
|
|
POSTGRES_PASSWORD: 'trading_pass_dev',
|
|
DATABASE_POSTGRES_HOST: 'pg.prod.internal',
|
|
DATABASE_POSTGRES_PORT: '5432',
|
|
DATABASE_POSTGRES_DATABASE: 'trading_bot',
|
|
DATABASE_POSTGRES_PASSWORD: 'trading_pass_dev',
|
|
MONGODB_URI: 'mongodb://prod:trading_mongo_dev@mongo.internal:27017/stock?authSource=admin',
|
|
DRAGONFLY_PASSWORD: 'strong_prod_redis_secret_987',
|
|
});
|
|
|
|
expect(badPgResult.exitCode).not.toBe(0);
|
|
expect(badPgResult.stderr).toMatch(/production PostgreSQL password/i);
|
|
});
|
|
});
|
|
|
|
describe('config loader .env isolation used by runInitInIsolatedSubprocess', () => {
|
|
// Arrange a parent dir whose .env would flip the dev target to QA PostgreSQL and leak a sentinel,
|
|
// then load config from a child dir with or without its own empty .env.
|
|
function loadFromChild(childHasEmptyEnv: boolean): {
|
|
exitCode: number;
|
|
stdout: string;
|
|
stderr: string;
|
|
} {
|
|
const parentDir = mkdtempSync(join(tmpdir(), 'stock-bot-db-migrate-parent-'));
|
|
const childDir = join(parentDir, 'child');
|
|
try {
|
|
mkdirSync(childDir);
|
|
writeFileSync(
|
|
join(parentDir, '.env'),
|
|
[
|
|
'DB_MIGRATE_ENV_LEAK_SENTINEL=leaked',
|
|
'POSTGRES_PORT=5432',
|
|
'POSTGRES_DATABASE=trading_bot',
|
|
'DATABASE_POSTGRES_PORT=5432',
|
|
'DATABASE_POSTGRES_DATABASE=trading_bot',
|
|
].join('\n'),
|
|
'utf8'
|
|
);
|
|
if (childHasEmptyEnv) {
|
|
writeFileSync(join(childDir, '.env'), '', 'utf8');
|
|
}
|
|
const script = `import { loadMigrationConfig, resolveMigrationTarget } from ${JSON.stringify(dbMigrateModuleUrl)};
|
|
const config = loadMigrationConfig();
|
|
const resolved = resolveMigrationTarget(config, process.env);
|
|
console.log(JSON.stringify({ sentinel: process.env.DB_MIGRATE_ENV_LEAK_SENTINEL ?? null, targetLabel: resolved.targetLabel }));`;
|
|
const result = Bun.spawnSync([process.execPath, '-e', script], {
|
|
cwd: childDir,
|
|
env: {
|
|
PATH: process.env.PATH ?? '',
|
|
HOME: childDir,
|
|
NODE_ENV: 'development',
|
|
POSTGRES_HOST: 'localhost',
|
|
DATABASE_POSTGRES_HOST: 'localhost',
|
|
POSTGRES_USERNAME: 'dev_user',
|
|
POSTGRES_PASSWORD: 'dev_pass',
|
|
},
|
|
});
|
|
return {
|
|
exitCode: result.exitCode,
|
|
stdout: new TextDecoder().decode(result.stdout).trim(),
|
|
stderr: new TextDecoder().decode(result.stderr).trim(),
|
|
};
|
|
} finally {
|
|
rmSync(parentDir, { recursive: true, force: true });
|
|
}
|
|
}
|
|
|
|
test('an empty .env in the working directory stops the loader from reading a parent .env', () => {
|
|
const result = loadFromChild(true);
|
|
|
|
expect(result.exitCode).toBe(0);
|
|
const parsed = JSON.parse(result.stdout) as { sentinel: string | null; targetLabel: string };
|
|
expect(parsed.sentinel).toBeNull();
|
|
// Defaults (no parent override) resolve to the isolated dev database, not QA.
|
|
expect(parsed.targetLabel).not.toBe('localhost:5432/trading_bot');
|
|
});
|
|
|
|
test('without the empty .env the parent .env leaks in and the QA target is rejected', () => {
|
|
const result = loadFromChild(false);
|
|
|
|
expect(result.exitCode).not.toBe(0);
|
|
expect(result.stderr).toMatch(/QA PostgreSQL/i);
|
|
});
|
|
});
|
|
|
|
describe('db-migrate CLI subprocess', () => {
|
|
test(
|
|
'exits non-zero with a clear message when the dev PostgreSQL target is unreachable',
|
|
() => {
|
|
const isolatedDir = mkdtempSync(join(tmpdir(), 'stock-bot-db-migrate-unreachable-'));
|
|
try {
|
|
writeFileSync(join(isolatedDir, '.env'), '', 'utf8');
|
|
const result = Bun.spawnSync(
|
|
[process.execPath, 'run', join(root, 'scripts/db-migrate.ts'), '--track', 'master'],
|
|
{
|
|
cwd: isolatedDir,
|
|
env: {
|
|
PATH: process.env.PATH ?? '',
|
|
HOME: isolatedDir,
|
|
NODE_ENV: 'development',
|
|
POSTGRES_HOST: '127.0.0.1',
|
|
POSTGRES_PORT: '1',
|
|
POSTGRES_DATABASE: 'trading_bot_dev',
|
|
DATABASE_POSTGRES_HOST: '127.0.0.1',
|
|
DATABASE_POSTGRES_PORT: '1',
|
|
DATABASE_POSTGRES_DATABASE: 'trading_bot_dev',
|
|
},
|
|
timeout: 30000,
|
|
}
|
|
);
|
|
const stdout = new TextDecoder().decode(result.stdout);
|
|
const stderr = new TextDecoder().decode(result.stderr);
|
|
|
|
expect(result.exitCode).toBe(1);
|
|
expect(stderr).toMatch(/db:migrate failed: .*connect/i);
|
|
expect(stdout).not.toMatch(/Applied \d+ migration/);
|
|
} finally {
|
|
rmSync(isolatedDir, { recursive: true, force: true });
|
|
}
|
|
},
|
|
40000
|
|
);
|
|
|
|
test('exits non-zero with valid tracks on stderr for --track bogus without connecting to DB', () => {
|
|
const result = Bun.spawnSync(
|
|
[process.execPath, 'run', 'scripts/db-migrate.ts', '--track', 'bogus'],
|
|
{ cwd: root }
|
|
);
|
|
expect(result.exitCode).not.toBe(0);
|
|
const stderr = new TextDecoder().decode(result.stderr);
|
|
expect(stderr).toMatch(/master\|research\|all/);
|
|
});
|
|
});
|