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: {
...rawConfig.database.mongodb,
...(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: {
...config.database.mongodb,
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 { resetStockConfig, stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config';
import { loadMigrationConfig, parseDbMigrateArgs, resolveMigrationTarget } from '../db-migrate';
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'];
@ -140,59 +144,64 @@ describe('resolveMigrationTarget', () => {
});
});
function withEnv(overrides: Record<string, string | undefined>, fn: () => void): void {
const previous = new Map<string, string | undefined>();
for (const [key, value] of Object.entries(overrides)) {
previous.set(key, process.env[key]);
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
resetStockConfig();
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-'));
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 {
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 {
resetStockConfig();
for (const [key, value] of previous.entries()) {
if (value === undefined) {
delete process.env[key];
} else {
process.env[key] = value;
}
}
rmSync(isolatedDir, { recursive: true, force: true });
}
}
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', () => {
withEnv(
{
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',
MONGODB_READ_URI: undefined,
STOCK_BOT_ALLOW_DEV_ON_QA_DB: undefined,
},
() => {
const config = loadMigrationConfig();
expect(config.database.mongodb.enabled).toBe(false);
const resolved = resolveMigrationTarget(config, process.env);
expect(resolved.targetLabel).toBe('localhost:5433/trading_bot_dev');
}
);
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', () => {
withEnv(
const result = runInitInIsolatedSubprocess(
{
NODE_ENV: 'development',
POSTGRES_HOST: 'localhost',
@ -201,31 +210,69 @@ describe('loadMigrationConfig (real initialization path)', () => {
DATABASE_POSTGRES_HOST: 'localhost',
DATABASE_POSTGRES_PORT: '5432',
DATABASE_POSTGRES_DATABASE: 'trading_bot',
STOCK_BOT_ALLOW_DEV_ON_QA_DB: undefined,
},
() => {
expect(() => loadMigrationConfig()).toThrow(/QA PostgreSQL/i);
}
'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', () => {
withEnv(
{
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',
},
() => {
const config = loadMigrationConfig();
expect(() => resolveMigrationTarget(config, process.env)).toThrow(/QA PostgreSQL/i);
}
);
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);
});
});