T-2: M0.2 — Finish shared Postgres migrations: bun run db:migrate + fresh-database schema test

This commit is contained in:
Studio 2026-11-27 10:43:36 -05:00
parent b82fc7c905
commit f36bdbd6bd
3 changed files with 125 additions and 68 deletions

View file

@ -42,7 +42,14 @@ export function initializeStockConfig(
mongodb: { mongodb: {
...rawConfig.database.mongodb, ...rawConfig.database.mongodb,
...(options?.mongoReadOnly === true ? { readOnly: true } : {}), ...(options?.mongoReadOnly === true ? { readOnly: true } : {}),
...(options?.postgresOnly === true ? { enabled: false } : {}), ...(options?.postgresOnly === true
? {
enabled: false,
uri: 'mongodb://disabled',
readUri: undefined,
password: undefined,
}
: {}),
}, },
}, },
} }

View file

@ -84,6 +84,9 @@ export function resolveMigrationTarget(
mongodb: { mongodb: {
...config.database.mongodb, ...config.database.mongodb,
enabled: false, enabled: false,
uri: 'mongodb://disabled',
readUri: undefined,
password: undefined,
}, },
}, },
}, },

View file

@ -1,9 +1,13 @@
import { fileURLToPath } from 'node:url'; import { mkdtempSync, rmSync } 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 { describe, expect, test } from 'bun:test';
import { resetStockConfig, stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config'; import { stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config';
import { loadMigrationConfig, parseDbMigrateArgs, resolveMigrationTarget } from '../db-migrate'; import { parseDbMigrateArgs, resolveMigrationTarget } from '../db-migrate';
const root = fileURLToPath(new URL('../../', import.meta.url)); const root = fileURLToPath(new URL('../../', import.meta.url));
const dbMigrateModuleUrl = pathToFileURL(join(root, 'scripts/db-migrate.ts')).href;
function makeConfig(overrides: { function makeConfig(overrides: {
environment?: StockAppConfig['environment']; environment?: StockAppConfig['environment'];
@ -140,59 +144,64 @@ describe('resolveMigrationTarget', () => {
}); });
}); });
function withEnv(overrides: Record<string, string | undefined>, fn: () => void): void { function runInitInIsolatedSubprocess(
const previous = new Map<string, string | undefined>(); env: Record<string, string>,
for (const [key, value] of Object.entries(overrides)) { mode: 'load-and-resolve' | 'load-only' = 'load-and-resolve'
previous.set(key, process.env[key]); ): { exitCode: number; stdout: string; stderr: string } {
if (value === undefined) { const isolatedDir = mkdtempSync(join(tmpdir(), 'stock-bot-db-migrate-env-'));
delete process.env[key]; const script =
} else { mode === 'load-only'
process.env[key] = value; ? `import { loadMigrationConfig } from ${JSON.stringify(dbMigrateModuleUrl)};
} const config = loadMigrationConfig();
} console.log(JSON.stringify({ mongoEnabled: config.database.mongodb.enabled }));`
resetStockConfig(); : `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 { try {
fn(); 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 { } finally {
resetStockConfig(); rmSync(isolatedDir, { recursive: true, force: true });
for (const [key, value] of previous.entries()) {
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
} }
} }
describe('loadMigrationConfig (real initialization path)', () => { describe('loadMigrationConfig (real initialization path, isolated subprocess)', () => {
test('succeeds for dev PostgreSQL even when QA MongoDB admin URI is set without MONGODB_READ_URI', () => { test('succeeds for dev PostgreSQL even when QA MongoDB admin URI is set without MONGODB_READ_URI', () => {
withEnv( const result = runInitInIsolatedSubprocess({
{ NODE_ENV: 'development',
NODE_ENV: 'development', POSTGRES_HOST: 'localhost',
POSTGRES_HOST: 'localhost', POSTGRES_PORT: '5433',
POSTGRES_PORT: '5433', POSTGRES_DATABASE: 'trading_bot_dev',
POSTGRES_DATABASE: 'trading_bot_dev', POSTGRES_USERNAME: 'dev_user',
POSTGRES_USERNAME: 'dev_user', POSTGRES_PASSWORD: 'dev_pass',
POSTGRES_PASSWORD: 'dev_pass', DATABASE_POSTGRES_HOST: 'localhost',
DATABASE_POSTGRES_HOST: 'localhost', DATABASE_POSTGRES_PORT: '5433',
DATABASE_POSTGRES_PORT: '5433', DATABASE_POSTGRES_DATABASE: 'trading_bot_dev',
DATABASE_POSTGRES_DATABASE: 'trading_bot_dev', MONGODB_URI: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin',
MONGODB_URI: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin', });
MONGODB_READ_URI: undefined,
STOCK_BOT_ALLOW_DEV_ON_QA_DB: undefined, expect(result.exitCode).toBe(0);
}, expect(JSON.parse(result.stdout)).toEqual({
() => { mongoEnabled: false,
const config = loadMigrationConfig(); targetLabel: 'localhost:5433/trading_bot_dev',
expect(config.database.mongodb.enabled).toBe(false); });
const resolved = resolveMigrationTarget(config, process.env);
expect(resolved.targetLabel).toBe('localhost:5433/trading_bot_dev');
}
);
}); });
test('rejects development targeting QA PostgreSQL during real config initialization', () => { test('rejects development targeting QA PostgreSQL during real config initialization', () => {
withEnv( const result = runInitInIsolatedSubprocess(
{ {
NODE_ENV: 'development', NODE_ENV: 'development',
POSTGRES_HOST: 'localhost', POSTGRES_HOST: 'localhost',
@ -201,31 +210,69 @@ describe('loadMigrationConfig (real initialization path)', () => {
DATABASE_POSTGRES_HOST: 'localhost', DATABASE_POSTGRES_HOST: 'localhost',
DATABASE_POSTGRES_PORT: '5432', DATABASE_POSTGRES_PORT: '5432',
DATABASE_POSTGRES_DATABASE: 'trading_bot', DATABASE_POSTGRES_DATABASE: 'trading_bot',
STOCK_BOT_ALLOW_DEV_ON_QA_DB: undefined,
}, },
() => { 'load-only'
expect(() => loadMigrationConfig()).toThrow(/QA PostgreSQL/i);
}
); );
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', () => { test('rejects development targeting QA PostgreSQL even when STOCK_BOT_ALLOW_DEV_ON_QA_DB=true in real env', () => {
withEnv( const result = runInitInIsolatedSubprocess({
{ NODE_ENV: 'development',
NODE_ENV: 'development', POSTGRES_HOST: 'localhost',
POSTGRES_HOST: 'localhost', POSTGRES_PORT: '5432',
POSTGRES_PORT: '5432', POSTGRES_DATABASE: 'trading_bot',
POSTGRES_DATABASE: 'trading_bot', DATABASE_POSTGRES_HOST: 'localhost',
DATABASE_POSTGRES_HOST: 'localhost', DATABASE_POSTGRES_PORT: '5432',
DATABASE_POSTGRES_PORT: '5432', DATABASE_POSTGRES_DATABASE: 'trading_bot',
DATABASE_POSTGRES_DATABASE: 'trading_bot', STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true',
STOCK_BOT_ALLOW_DEV_ON_QA_DB: 'true', });
},
() => { expect(result.exitCode).not.toBe(0);
const config = loadMigrationConfig(); expect(result.stderr).toMatch(/QA PostgreSQL/i);
expect(() => resolveMigrationTarget(config, process.env)).toThrow(/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);
}); });
}); });