Compare commits
No commits in common. "f712c3619bda5c2aaf6fc7bacbce838d5c032b2c" and "890761e0d56953db2907c032d49e59e0a36c8d00" have entirely different histories.
f712c3619b
...
890761e0d5
47 changed files with 628 additions and 3150 deletions
|
|
@ -13,7 +13,6 @@ const __dirname = path.dirname(__filename);
|
|||
|
||||
export interface InitializeStockConfigOptions {
|
||||
mongoReadOnly?: boolean;
|
||||
postgresOnly?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
|
|
@ -34,22 +33,14 @@ export function initializeStockConfig(
|
|||
|
||||
const rawConfig = configInstance.initialize(stockAppSchema);
|
||||
const config: StockAppConfig =
|
||||
options?.mongoReadOnly === true || options?.postgresOnly === true
|
||||
options?.mongoReadOnly === true
|
||||
? {
|
||||
...rawConfig,
|
||||
database: {
|
||||
...rawConfig.database,
|
||||
mongodb: {
|
||||
...rawConfig.database.mongodb,
|
||||
...(options?.mongoReadOnly === true ? { readOnly: true } : {}),
|
||||
...(options?.postgresOnly === true
|
||||
? {
|
||||
enabled: false,
|
||||
uri: 'mongodb://disabled',
|
||||
readUri: undefined,
|
||||
password: undefined,
|
||||
}
|
||||
: {}),
|
||||
readOnly: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,19 +2,7 @@ import type { StockAppConfig } from './schemas';
|
|||
|
||||
export type StockServiceName = 'dataIngestion' | 'dataPipeline' | 'webApi' | 'orchestrator';
|
||||
|
||||
interface MongoTargetHost {
|
||||
host: string;
|
||||
port?: number;
|
||||
}
|
||||
|
||||
interface ParsedMongoTarget {
|
||||
hosts: MongoTargetHost[];
|
||||
host?: string;
|
||||
database?: string;
|
||||
username?: string;
|
||||
}
|
||||
|
||||
const LOOPBACK_HOSTS = new Set(['localhost', '0.0.0.0']);
|
||||
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '0.0.0.0']);
|
||||
const FORBIDDEN_PROD_SECRETS = new Set([
|
||||
'trading_pass_dev',
|
||||
'trading_mongo_dev',
|
||||
|
|
@ -24,271 +12,41 @@ const FORBIDDEN_PROD_SECRETS = new Set([
|
|||
'admin123',
|
||||
]);
|
||||
|
||||
function parseIpv4Octets(host: string): [number, number, number, number] | null {
|
||||
const octets = host.split('.');
|
||||
if (octets.length !== 4) {
|
||||
return null;
|
||||
}
|
||||
const values: number[] = [];
|
||||
for (const part of octets) {
|
||||
if (!/^\d{1,3}$/.test(part)) {
|
||||
return null;
|
||||
}
|
||||
const value = Number(part);
|
||||
if (value < 0 || value > 255) {
|
||||
return null;
|
||||
}
|
||||
values.push(value);
|
||||
}
|
||||
const [a, b, c, d] = values;
|
||||
if (a === undefined || b === undefined || c === undefined || d === undefined) {
|
||||
return null;
|
||||
}
|
||||
return [a, b, c, d];
|
||||
}
|
||||
|
||||
function isIpv4Loopback(host: string): boolean {
|
||||
const octets = parseIpv4Octets(host);
|
||||
return octets !== null && octets[0] === 127;
|
||||
}
|
||||
|
||||
function parseIpv6Side(side: string, allowIpv4Tail: boolean): number[] | null {
|
||||
if (side === '') {
|
||||
return [];
|
||||
}
|
||||
const parts = side.split(':');
|
||||
const groups: number[] = [];
|
||||
for (let i = 0; i < parts.length; i++) {
|
||||
const part = parts[i];
|
||||
if (part === undefined) {
|
||||
return null;
|
||||
}
|
||||
if (i === parts.length - 1 && allowIpv4Tail && part.includes('.')) {
|
||||
const octets = parseIpv4Octets(part);
|
||||
if (!octets) {
|
||||
return null;
|
||||
}
|
||||
groups.push((octets[0] << 8) | octets[1], (octets[2] << 8) | octets[3]);
|
||||
continue;
|
||||
}
|
||||
if (!/^[0-9a-f]{1,4}$/i.test(part)) {
|
||||
return null;
|
||||
}
|
||||
groups.push(parseInt(part, 16));
|
||||
}
|
||||
return groups;
|
||||
}
|
||||
|
||||
function parseIpv6Hextets(host: string): number[] | null {
|
||||
if (!host.includes(':')) {
|
||||
return null;
|
||||
}
|
||||
const zoneIdx = host.indexOf('%');
|
||||
const addr = zoneIdx >= 0 ? host.slice(0, zoneIdx) : host;
|
||||
const halves = addr.split('::');
|
||||
if (halves.length > 2) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const firstHalf = halves[0];
|
||||
if (firstHalf === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (halves.length === 1) {
|
||||
const groups = parseIpv6Side(firstHalf, true);
|
||||
return groups && groups.length === 8 ? groups : null;
|
||||
}
|
||||
|
||||
const secondHalf = halves[1];
|
||||
if (secondHalf === undefined) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const left = parseIpv6Side(firstHalf, false);
|
||||
const right = parseIpv6Side(secondHalf, true);
|
||||
if (!left || !right) {
|
||||
return null;
|
||||
}
|
||||
const missing = 8 - left.length - right.length;
|
||||
if (missing < 1) {
|
||||
return null;
|
||||
}
|
||||
return [...left, ...Array<number>(missing).fill(0), ...right];
|
||||
}
|
||||
|
||||
function isIpv6Loopback(host: string): boolean {
|
||||
const hextets = parseIpv6Hextets(host);
|
||||
if (!hextets) {
|
||||
return false;
|
||||
}
|
||||
const [h0, h1, h2, h3, h4, h5, h6, h7] = hextets;
|
||||
if (
|
||||
h0 === undefined ||
|
||||
h1 === undefined ||
|
||||
h2 === undefined ||
|
||||
h3 === undefined ||
|
||||
h4 === undefined ||
|
||||
h5 === undefined ||
|
||||
h6 === undefined ||
|
||||
h7 === undefined
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
if (h0 === 0 && h1 === 0 && h2 === 0 && h3 === 0 && h4 === 0 && h5 === 0 && h6 === 0) {
|
||||
return h7 === 0 || h7 === 1;
|
||||
}
|
||||
// IPv4-mapped IPv6 (::ffff:0:0/96): match 127.0.0.0/8 and 0.0.0.0 in both dotted and hex forms
|
||||
if (h0 === 0 && h1 === 0 && h2 === 0 && h3 === 0 && h4 === 0 && h5 === 0xffff) {
|
||||
const firstOctet = (h6 >> 8) & 0xff;
|
||||
return firstOctet === 127 || (h6 === 0 && h7 === 0);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
function isLoopbackHost(host?: string): boolean {
|
||||
if (!host) {
|
||||
return false;
|
||||
}
|
||||
const normalized = host
|
||||
.trim()
|
||||
.replace(/^\[|\]$/g, '')
|
||||
.replace(/\.+$/, '')
|
||||
.toLowerCase();
|
||||
return (
|
||||
LOOPBACK_HOSTS.has(normalized) ||
|
||||
isIpv4Loopback(normalized) ||
|
||||
isIpv6Loopback(normalized)
|
||||
);
|
||||
const normalized = host.replace(/^\[|\]$/g, '').toLowerCase();
|
||||
return LOOPBACK_HOSTS.has(normalized);
|
||||
}
|
||||
|
||||
function parseMongoHostPort(
|
||||
segment: string,
|
||||
defaultPort: number | undefined
|
||||
): MongoTargetHost | null {
|
||||
const trimmed = segment.trim();
|
||||
if (!trimmed) {
|
||||
return null;
|
||||
function parseMongoTarget(uri?: string): {
|
||||
host?: string;
|
||||
port?: number;
|
||||
database?: string;
|
||||
username?: string;
|
||||
} {
|
||||
if (!uri) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (trimmed.startsWith('[')) {
|
||||
const closeIdx = trimmed.indexOf(']');
|
||||
if (closeIdx <= 1) {
|
||||
return null;
|
||||
}
|
||||
const host = trimmed.slice(1, closeIdx).trim();
|
||||
if (!host) {
|
||||
return null;
|
||||
}
|
||||
const after = trimmed.slice(closeIdx + 1).trim();
|
||||
if (after === '' || after === ':') {
|
||||
return { host, port: defaultPort };
|
||||
}
|
||||
if (!after.startsWith(':')) {
|
||||
return null;
|
||||
}
|
||||
const portStr = after.slice(1).trim();
|
||||
if (!/^\d+$/.test(portStr)) {
|
||||
return null;
|
||||
}
|
||||
const port = Number(portStr);
|
||||
if (port < 1 || port > 65535) {
|
||||
return null;
|
||||
}
|
||||
return { host, port };
|
||||
try {
|
||||
const parsed = new URL(uri);
|
||||
const database = parsed.pathname.replace(/^\/+/, '').split('/')[0] || undefined;
|
||||
const port = parsed.port ? Number(parsed.port) : parsed.protocol === 'mongodb:' ? 27017 : undefined;
|
||||
return {
|
||||
host: parsed.hostname || undefined,
|
||||
port: Number.isFinite(port) ? port : undefined,
|
||||
database,
|
||||
username: parsed.username ? decodeURIComponent(parsed.username) : undefined,
|
||||
};
|
||||
} catch {
|
||||
return {};
|
||||
}
|
||||
|
||||
const colonIdx = trimmed.indexOf(':');
|
||||
if (colonIdx === -1) {
|
||||
return { host: trimmed, port: defaultPort };
|
||||
}
|
||||
if (trimmed.indexOf(':', colonIdx + 1) !== -1) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const host = trimmed.slice(0, colonIdx).trim();
|
||||
const portStr = trimmed.slice(colonIdx + 1).trim();
|
||||
if (!host) {
|
||||
return null;
|
||||
}
|
||||
if (portStr === '') {
|
||||
return { host, port: defaultPort };
|
||||
}
|
||||
if (!/^\d+$/.test(portStr)) {
|
||||
return null;
|
||||
}
|
||||
const port = Number(portStr);
|
||||
if (port < 1 || port > 65535) {
|
||||
return null;
|
||||
}
|
||||
return { host, port };
|
||||
}
|
||||
|
||||
function parseMongoTarget(uri?: string): ParsedMongoTarget {
|
||||
const trimmed = uri?.trim();
|
||||
if (!trimmed) {
|
||||
return { hosts: [] };
|
||||
}
|
||||
|
||||
const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/i.exec(trimmed);
|
||||
const rawScheme = schemeMatch?.[1];
|
||||
const rest = schemeMatch?.[2];
|
||||
if (!rawScheme || rest === undefined) {
|
||||
return { hosts: [] };
|
||||
}
|
||||
|
||||
const scheme = rawScheme.toLowerCase();
|
||||
const defaultPort = scheme === 'mongodb' ? 27017 : undefined;
|
||||
|
||||
const delimiterMatch = /[/?#]/.exec(rest);
|
||||
const authority = delimiterMatch ? rest.slice(0, delimiterMatch.index) : rest;
|
||||
const remainder = delimiterMatch ? rest.slice(delimiterMatch.index) : '';
|
||||
|
||||
let database: string | undefined;
|
||||
if (remainder.startsWith('/')) {
|
||||
const pathPart = remainder.split(/[?#]/, 1)[0] ?? '';
|
||||
const firstSegment = pathPart.replace(/^\/+/, '').split('/')[0];
|
||||
database = firstSegment || undefined;
|
||||
}
|
||||
|
||||
const atIndex = authority.lastIndexOf('@');
|
||||
const userinfo = atIndex >= 0 ? authority.slice(0, atIndex) : '';
|
||||
const hostList = atIndex >= 0 ? authority.slice(atIndex + 1) : authority;
|
||||
|
||||
let username: string | undefined;
|
||||
if (userinfo) {
|
||||
const colonIndex = userinfo.indexOf(':');
|
||||
const rawUsername = colonIndex >= 0 ? userinfo.slice(0, colonIndex) : userinfo;
|
||||
if (rawUsername) {
|
||||
try {
|
||||
username = decodeURIComponent(rawUsername);
|
||||
} catch {
|
||||
username = rawUsername;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const hosts: MongoTargetHost[] = [];
|
||||
for (const segment of hostList.split(',')) {
|
||||
const parsedHost = parseMongoHostPort(segment, defaultPort);
|
||||
if (parsedHost) {
|
||||
hosts.push(parsedHost);
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
hosts,
|
||||
host: hosts[0]?.host,
|
||||
database,
|
||||
username,
|
||||
};
|
||||
}
|
||||
|
||||
function isQaMongoTarget(uri: string | undefined): boolean {
|
||||
const target = parseMongoTarget(uri);
|
||||
return target.hosts.some(
|
||||
entry => isLoopbackHost(entry.host) && (entry.port === undefined || entry.port === 27017)
|
||||
);
|
||||
return isLoopbackHost(target.host) && target.port === 27017;
|
||||
}
|
||||
|
||||
function isQaPostgresTarget(pg: StockAppConfig['database']['postgres']): boolean {
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import { getExchangeStats } from './operations/exchange-stats.operations';
|
|||
import { getProviderMappingStats } from './operations/provider-mapping-stats.operations';
|
||||
import { syncQMExchanges } from './operations/qm-exchanges.operations';
|
||||
import { syncAllExchanges } from './operations/sync-all-exchanges.operations';
|
||||
import { syncIBExchanges } from './operations/sync-ib-exchanges.operations';
|
||||
import { syncQMProviderMappings } from './operations/sync-qm-provider-mappings.operations';
|
||||
|
||||
@Handler('exchanges')
|
||||
|
|
@ -40,6 +41,19 @@ class ExchangesHandler extends BaseHandler {
|
|||
return syncQMExchanges({}, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync exchanges from Interactive Brokers
|
||||
*/
|
||||
@Operation('sync-ib-exchanges')
|
||||
@ScheduledOperation('sync-ib-exchanges', '0 3 * * *', {
|
||||
priority: 3,
|
||||
description: 'Daily sync of IB exchanges at 3 AM',
|
||||
})
|
||||
async syncIBExchanges(): Promise<unknown> {
|
||||
this.log('info', 'Starting IB exchanges sync...');
|
||||
return syncIBExchanges({}, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Sync provider mappings from QuestionsAndMethods
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -0,0 +1,212 @@
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { MasterExchange } from '@stock-bot/mongodb';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import type { JobPayload } from '../../../types/job-payloads';
|
||||
|
||||
const logger = getLogger('sync-ib-exchanges');
|
||||
|
||||
interface IBExchange {
|
||||
id?: string;
|
||||
_id?: unknown;
|
||||
name?: string;
|
||||
code?: string;
|
||||
country_code?: string;
|
||||
currency?: string;
|
||||
}
|
||||
|
||||
export async function syncIBExchanges(
|
||||
payload: JobPayload,
|
||||
container: IServiceContainer
|
||||
): Promise<{ syncedCount: number; totalExchanges: number }> {
|
||||
logger.info('Syncing IB exchanges from database...');
|
||||
|
||||
try {
|
||||
const { mongodb: mongoClient } = requireServices(container, 'mongodb');
|
||||
const db = mongoClient.getDatabase();
|
||||
|
||||
// Filter by country code US and CA
|
||||
const ibExchanges = await db
|
||||
.collection<IBExchange>('ibExchanges')
|
||||
.find({
|
||||
country_code: { $in: ['US', 'CA'] },
|
||||
})
|
||||
.toArray();
|
||||
|
||||
logger.info('Found IB exchanges in database', { count: ibExchanges.length });
|
||||
|
||||
let syncedCount = 0;
|
||||
|
||||
for (const exchange of ibExchanges) {
|
||||
try {
|
||||
await createOrUpdateMasterExchange(exchange, container);
|
||||
syncedCount++;
|
||||
|
||||
logger.debug('Synced IB exchange', {
|
||||
ibId: exchange.id,
|
||||
country: exchange.country_code,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error('Failed to sync IB exchange', { exchange: exchange.id, error });
|
||||
}
|
||||
}
|
||||
|
||||
logger.info('IB exchange sync completed', {
|
||||
syncedCount,
|
||||
totalExchanges: ibExchanges.length,
|
||||
});
|
||||
|
||||
return { syncedCount, totalExchanges: ibExchanges.length };
|
||||
} catch (error) {
|
||||
logger.error('Failed to fetch IB exchanges from database', { error });
|
||||
return { syncedCount: 0, totalExchanges: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create or update master exchange record 1:1 from IB exchange
|
||||
*/
|
||||
async function createOrUpdateMasterExchange(
|
||||
ibExchange: IBExchange,
|
||||
container: IServiceContainer
|
||||
): Promise<void> {
|
||||
const { mongodb: mongoClient } = requireServices(container, 'mongodb');
|
||||
const db = mongoClient.getDatabase();
|
||||
const collection = db.collection<MasterExchange>('masterExchanges');
|
||||
|
||||
const masterExchangeId = generateMasterExchangeId(ibExchange);
|
||||
const now = new Date();
|
||||
|
||||
// Check if master exchange already exists
|
||||
const existing = await collection.findOne({ masterExchangeId });
|
||||
|
||||
if (existing) {
|
||||
// Update existing record
|
||||
await collection.updateOne(
|
||||
{ masterExchangeId },
|
||||
{
|
||||
$set: {
|
||||
officialName: ibExchange.name || `Exchange ${ibExchange.id}`,
|
||||
country: ibExchange.country_code || 'UNKNOWN',
|
||||
currency: ibExchange.currency || 'USD',
|
||||
timezone: inferTimezone(ibExchange),
|
||||
updated_at: now,
|
||||
},
|
||||
}
|
||||
);
|
||||
|
||||
logger.debug('Updated existing master exchange', { masterExchangeId });
|
||||
} else {
|
||||
// Create new master exchange
|
||||
const masterExchange: MasterExchange = {
|
||||
masterExchangeId,
|
||||
shortName: masterExchangeId, // Set shortName to masterExchangeId on creation
|
||||
officialName: ibExchange.name || `Exchange ${ibExchange.id}`,
|
||||
country: ibExchange.country_code || 'UNKNOWN',
|
||||
currency: ibExchange.currency || 'USD',
|
||||
timezone: inferTimezone(ibExchange),
|
||||
active: false, // Set active to false only on creation
|
||||
|
||||
sourceMappings: {
|
||||
ib: {
|
||||
id: ibExchange.id || ibExchange._id?.toString() || 'unknown',
|
||||
name: ibExchange.name || `Exchange ${ibExchange.id}`,
|
||||
code: ibExchange.code || ibExchange.id || '',
|
||||
aliases: generateAliases(ibExchange),
|
||||
lastUpdated: now,
|
||||
},
|
||||
},
|
||||
|
||||
confidence: 1.0, // High confidence for direct IB mapping
|
||||
verified: true, // Mark as verified since it's direct from IB
|
||||
|
||||
// DocumentBase fields
|
||||
source: 'ib-exchange-sync',
|
||||
created_at: now,
|
||||
updated_at: now,
|
||||
};
|
||||
|
||||
await collection.insertOne(masterExchange);
|
||||
logger.debug('Created new master exchange', { masterExchangeId });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate master exchange ID from IB exchange
|
||||
*/
|
||||
function generateMasterExchangeId(ibExchange: IBExchange): string {
|
||||
// Use code if available, otherwise use ID, otherwise generate from name
|
||||
if (ibExchange.code) {
|
||||
return ibExchange.code.toUpperCase().replace(/[^A-Z0-9]/g, '');
|
||||
}
|
||||
|
||||
if (ibExchange.id) {
|
||||
return ibExchange.id.toUpperCase().replace(/[^A-Z0-9]/g, '');
|
||||
}
|
||||
|
||||
if (ibExchange.name) {
|
||||
return ibExchange.name
|
||||
.toUpperCase()
|
||||
.split(' ')
|
||||
.slice(0, 2)
|
||||
.join('_')
|
||||
.replace(/[^A-Z0-9_]/g, '');
|
||||
}
|
||||
|
||||
return 'UNKNOWN_EXCHANGE';
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate aliases for the exchange
|
||||
*/
|
||||
function generateAliases(ibExchange: IBExchange): string[] {
|
||||
const aliases: string[] = [];
|
||||
|
||||
if (ibExchange.name && ibExchange.name.includes(' ')) {
|
||||
// Add abbreviated version
|
||||
aliases.push(
|
||||
ibExchange.name
|
||||
.split(' ')
|
||||
.map(w => w[0])
|
||||
.join('')
|
||||
.toUpperCase()
|
||||
);
|
||||
}
|
||||
|
||||
if (ibExchange.code) {
|
||||
aliases.push(ibExchange.code.toUpperCase());
|
||||
}
|
||||
|
||||
return aliases;
|
||||
}
|
||||
|
||||
/**
|
||||
* Infer timezone from exchange name/location
|
||||
*/
|
||||
function inferTimezone(ibExchange: IBExchange): string {
|
||||
if (!ibExchange.name) {
|
||||
return 'UTC';
|
||||
}
|
||||
|
||||
const name = ibExchange.name.toUpperCase();
|
||||
|
||||
if (name.includes('NEW YORK') || name.includes('NYSE') || name.includes('NASDAQ')) {
|
||||
return 'America/New_York';
|
||||
}
|
||||
if (name.includes('LONDON')) {
|
||||
return 'Europe/London';
|
||||
}
|
||||
if (name.includes('TOKYO')) {
|
||||
return 'Asia/Tokyo';
|
||||
}
|
||||
if (name.includes('SHANGHAI')) {
|
||||
return 'Asia/Shanghai';
|
||||
}
|
||||
if (name.includes('TORONTO')) {
|
||||
return 'America/Toronto';
|
||||
}
|
||||
if (name.includes('FRANKFURT')) {
|
||||
return 'Europe/Berlin';
|
||||
}
|
||||
|
||||
return 'UTC'; // Default
|
||||
}
|
||||
|
|
@ -73,6 +73,16 @@ export function createPipelineRoutes(container: IServiceContainer) {
|
|||
}
|
||||
});
|
||||
|
||||
pipeline.post('/provider-mappings/ib', async c => {
|
||||
try {
|
||||
const result = await pipelineService.syncIBExchanges();
|
||||
return c.json(result, result.success ? 200 : 503);
|
||||
} catch (error) {
|
||||
logger.error('Error in POST /provider-mappings/ib', { error });
|
||||
return c.json({ success: false, error: 'Internal server error' }, 500);
|
||||
}
|
||||
});
|
||||
|
||||
// Status endpoint
|
||||
pipeline.get('/status', async c => {
|
||||
try {
|
||||
|
|
|
|||
|
|
@ -182,6 +182,38 @@ export class PipelineService {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue a job to sync IB exchanges
|
||||
*/
|
||||
async syncIBExchanges(): Promise<PipelineJobResult> {
|
||||
try {
|
||||
const queueManager = this.container.queueManager;
|
||||
if (!queueManager) {
|
||||
return { success: false, error: 'Queue manager not available' };
|
||||
}
|
||||
|
||||
const exchangesQueue = queueManager.getQueue(getFullQueueName('data-pipeline', 'exchanges'));
|
||||
const job = await exchangesQueue.add('sync-ib-exchanges', {
|
||||
handler: 'exchanges',
|
||||
operation: 'sync-ib-exchanges',
|
||||
payload: {},
|
||||
});
|
||||
|
||||
logger.info('IB exchanges sync job queued', { jobId: job.id });
|
||||
return {
|
||||
success: true,
|
||||
jobId: job.id,
|
||||
message: 'IB exchanges sync job queued',
|
||||
};
|
||||
} catch (error) {
|
||||
logger.error('Failed to queue IB exchanges sync job', { error });
|
||||
return {
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to queue sync job',
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get sync status
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -59,6 +59,14 @@ const operations: PipelineOperation[] = [
|
|||
method: 'POST',
|
||||
category: 'sync',
|
||||
},
|
||||
{
|
||||
id: 'sync-ib-exchanges',
|
||||
name: 'Sync IB Exchanges',
|
||||
description: 'Sync exchanges from Interactive Brokers',
|
||||
endpoint: '/provider-mappings/ib',
|
||||
method: 'POST',
|
||||
category: 'sync',
|
||||
},
|
||||
// Maintenance operations
|
||||
{
|
||||
id: 'clear-postgresql',
|
||||
|
|
@ -81,6 +89,7 @@ export function PipelinePage() {
|
|||
syncQMExchanges,
|
||||
syncAllExchanges,
|
||||
syncQMProviderMappings,
|
||||
syncIBExchanges,
|
||||
clearPostgreSQLData,
|
||||
getExchangeStats,
|
||||
getProviderMappingStats,
|
||||
|
|
@ -127,6 +136,9 @@ export function PipelinePage() {
|
|||
case 'sync-qm-provider-mappings':
|
||||
await syncQMProviderMappings();
|
||||
break;
|
||||
case 'sync-ib-exchanges':
|
||||
await syncIBExchanges();
|
||||
break;
|
||||
case 'clear-postgresql':
|
||||
{
|
||||
const expected = `DELETE STOCK REFERENCE DATA:${clearDataType}`;
|
||||
|
|
|
|||
|
|
@ -65,6 +65,11 @@ export function usePipeline() {
|
|||
[executeOperation]
|
||||
);
|
||||
|
||||
const syncIBExchanges = useCallback(
|
||||
() => executeOperation(() => pipelineApi.syncIBExchanges()),
|
||||
[executeOperation]
|
||||
);
|
||||
|
||||
// Maintenance operations
|
||||
const clearPostgreSQLData = useCallback(
|
||||
(dataType: DataClearType, confirmation: string) =>
|
||||
|
|
@ -143,6 +148,7 @@ export function usePipeline() {
|
|||
|
||||
// Provider mapping operations
|
||||
syncQMProviderMappings,
|
||||
syncIBExchanges,
|
||||
|
||||
// Maintenance operations
|
||||
clearPostgreSQLData,
|
||||
|
|
|
|||
|
|
@ -46,6 +46,10 @@ class PipelineApiService {
|
|||
return this.request<PipelineJobResult>('/provider-mappings/qm', { method: 'POST' });
|
||||
}
|
||||
|
||||
async syncIBExchanges(): Promise<PipelineJobResult> {
|
||||
return this.request<PipelineJobResult>('/provider-mappings/ib', { method: 'POST' });
|
||||
}
|
||||
|
||||
// Status and maintenance operations
|
||||
async getSyncStatus(): Promise<PipelineJobResult> {
|
||||
return this.request<PipelineJobResult>('/status');
|
||||
|
|
|
|||
|
|
@ -2,7 +2,7 @@
|
|||
|
||||
-- Exchanges Table
|
||||
CREATE TABLE IF NOT EXISTS exchanges (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
code VARCHAR(10) UNIQUE NOT NULL, -- NASDAQ, NYSE, TSX, etc.
|
||||
name VARCHAR(255) NOT NULL, -- Full exchange name
|
||||
country CHAR(2) NOT NULL, -- US, CA, GB
|
||||
|
|
@ -14,7 +14,7 @@ CREATE TABLE IF NOT EXISTS exchanges (
|
|||
|
||||
-- Symbols Table
|
||||
CREATE TABLE IF NOT EXISTS symbols (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
symbol VARCHAR(20) NOT NULL, -- AAPL, SHOP, etc.
|
||||
exchange_id UUID REFERENCES exchanges(id),
|
||||
company_name VARCHAR(255),
|
||||
|
|
@ -29,7 +29,7 @@ CREATE TABLE IF NOT EXISTS symbols (
|
|||
|
||||
-- Provider Symbol Mappings (How each provider refers to our symbols)
|
||||
CREATE TABLE IF NOT EXISTS provider_mappings (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
symbol_id UUID REFERENCES symbols(id),
|
||||
provider VARCHAR(50) NOT NULL, -- 'qm', 'yahoo', 'ib', etc.
|
||||
provider_symbol VARCHAR(100) NOT NULL, -- How provider names it: "AAPL:NASDAQ", "SHOP.TO"
|
||||
|
|
@ -43,7 +43,7 @@ CREATE TABLE IF NOT EXISTS provider_mappings (
|
|||
|
||||
-- Simple sync tracking table
|
||||
CREATE TABLE IF NOT EXISTS sync_status (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
provider VARCHAR(50) NOT NULL,
|
||||
data_type VARCHAR(50) NOT NULL, -- 'symbols', 'exchanges'
|
||||
last_sync_at TIMESTAMP,
|
||||
|
|
|
|||
|
|
@ -19,7 +19,7 @@ END $$;
|
|||
-- Provider Exchange Mappings Table
|
||||
-- Maps provider-specific exchange codes to our master exchanges
|
||||
CREATE TABLE IF NOT EXISTS provider_exchange_mappings (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
id UUID PRIMARY KEY DEFAULT uuid_generate_v4(),
|
||||
provider VARCHAR(50) NOT NULL, -- 'qm', 'eod', 'ib', etc.
|
||||
provider_exchange_code VARCHAR(50) NOT NULL, -- Provider's exchange code: 'NYE', 'US', 'NASDAQ'
|
||||
provider_exchange_name VARCHAR(255), -- Provider's exchange name
|
||||
|
|
|
|||
71
libs/core/cache/test/redis-cache.test.ts
vendored
71
libs/core/cache/test/redis-cache.test.ts
vendored
|
|
@ -1,55 +1,21 @@
|
|||
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
|
||||
import { beforeEach, describe, expect, it } from 'bun:test';
|
||||
import { RedisCache } from '../src/redis-cache';
|
||||
import type { CacheOptions, RedisConfig } from '../src/types';
|
||||
import type { CacheOptions } from '../src/types';
|
||||
|
||||
const testRedisUrl = process.env.BACKTEST_TEST_REDIS_URL;
|
||||
const hasTestRedis = Boolean(process.env.BACKTEST_TEST_REDIS_URL);
|
||||
|
||||
function parseTestRedisConfig(rawUrl: string): RedisConfig {
|
||||
const parsed = new URL(rawUrl);
|
||||
if (parsed.pathname !== '/15') {
|
||||
throw new Error('BACKTEST_TEST_REDIS_URL must point to dedicated Redis database /15');
|
||||
}
|
||||
return {
|
||||
host: parsed.hostname,
|
||||
port: parsed.port ? Number(parsed.port) : 6379,
|
||||
db: 15,
|
||||
...(parsed.username ? { username: decodeURIComponent(parsed.username) } : {}),
|
||||
...(parsed.password ? { password: decodeURIComponent(parsed.password) } : {}),
|
||||
};
|
||||
}
|
||||
|
||||
if (!testRedisUrl) {
|
||||
process.stderr.write(
|
||||
'Skipping RedisCache integration tests: set BACKTEST_TEST_REDIS_URL to a dedicated Redis fixture using database /15\n'
|
||||
);
|
||||
}
|
||||
|
||||
describe.skipIf(!testRedisUrl)('RedisCache', () => {
|
||||
describe.skipIf(!hasTestRedis)('RedisCache', () => {
|
||||
let cache: RedisCache;
|
||||
let redisConfig: RedisConfig;
|
||||
let testPrefix: string;
|
||||
|
||||
beforeEach(() => {
|
||||
redisConfig = parseTestRedisConfig(testRedisUrl!);
|
||||
testPrefix = `test:${crypto.randomUUID()}:`;
|
||||
const options: CacheOptions = {
|
||||
keyPrefix: testPrefix,
|
||||
keyPrefix: 'test:',
|
||||
ttl: 3600,
|
||||
shared: false,
|
||||
redisConfig,
|
||||
redisConfig: { host: 'localhost', port: 6379 },
|
||||
};
|
||||
cache = new RedisCache(options);
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
if (!cache) return;
|
||||
try {
|
||||
await cache.clear();
|
||||
} finally {
|
||||
await cache.disconnect();
|
||||
}
|
||||
});
|
||||
|
||||
describe('Core functionality', () => {
|
||||
it('should create cache instance', () => {
|
||||
expect(cache).toBeDefined();
|
||||
|
|
@ -181,26 +147,17 @@ describe.skipIf(!testRedisUrl)('RedisCache', () => {
|
|||
it('should handle errors gracefully in get', async () => {
|
||||
// Force an error by using invalid JSON
|
||||
const badCache = new RedisCache({
|
||||
keyPrefix: `bad:${crypto.randomUUID()}:`,
|
||||
shared: false,
|
||||
redisConfig,
|
||||
keyPrefix: 'bad:',
|
||||
redisConfig: { host: 'localhost', port: 6379 },
|
||||
});
|
||||
|
||||
try {
|
||||
// This would normally throw but should return null
|
||||
const result = await badCache.get('non-existent');
|
||||
expect(result).toBeNull();
|
||||
// This would normally throw but should return null
|
||||
const result = await badCache.get('non-existent');
|
||||
expect(result).toBeNull();
|
||||
|
||||
// Check stats updated
|
||||
const stats = badCache.getStats();
|
||||
expect(stats.misses).toBe(1);
|
||||
} finally {
|
||||
try {
|
||||
await badCache.clear();
|
||||
} finally {
|
||||
await badCache.disconnect();
|
||||
}
|
||||
}
|
||||
// Check stats updated
|
||||
const stats = badCache.getStats();
|
||||
expect(stats.misses).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -33,103 +33,11 @@ export const questdbConfigSchema = z.object({
|
|||
.describe('Deprecated: no effect on QuestDB client/writer'),
|
||||
});
|
||||
|
||||
function isValidMongoHostSegment(segment: string, allowPort: boolean): boolean {
|
||||
if (!segment || /\s/.test(segment)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (segment.startsWith('[')) {
|
||||
const closeIdx = segment.indexOf(']');
|
||||
if (closeIdx <= 1) {
|
||||
return false;
|
||||
}
|
||||
const host = segment.slice(1, closeIdx);
|
||||
if (!host || host.includes('[') || host.includes(']')) {
|
||||
return false;
|
||||
}
|
||||
const after = segment.slice(closeIdx + 1);
|
||||
if (after === '') {
|
||||
return true;
|
||||
}
|
||||
if (!allowPort || !after.startsWith(':')) {
|
||||
return false;
|
||||
}
|
||||
const portStr = after.slice(1);
|
||||
if (portStr === '') {
|
||||
return true;
|
||||
}
|
||||
if (!/^\d+$/.test(portStr)) {
|
||||
return false;
|
||||
}
|
||||
const port = Number(portStr);
|
||||
return port >= 1 && port <= 65535;
|
||||
}
|
||||
|
||||
const colonIdx = segment.indexOf(':');
|
||||
if (colonIdx === -1) {
|
||||
return true;
|
||||
}
|
||||
if (!allowPort || segment.indexOf(':', colonIdx + 1) !== -1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const host = segment.slice(0, colonIdx);
|
||||
const portStr = segment.slice(colonIdx + 1);
|
||||
if (!host) {
|
||||
return false;
|
||||
}
|
||||
if (portStr === '') {
|
||||
return true;
|
||||
}
|
||||
if (!/^\d+$/.test(portStr)) {
|
||||
return false;
|
||||
}
|
||||
const port = Number(portStr);
|
||||
return port >= 1 && port <= 65535;
|
||||
}
|
||||
|
||||
function isValidMongoUri(uri: string): boolean {
|
||||
if (!uri || /\s/.test(uri)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const schemeMatch = /^(mongodb(?:\+srv)?):\/\/(.*)$/i.exec(uri);
|
||||
const rawScheme = schemeMatch?.[1];
|
||||
const rest = schemeMatch?.[2];
|
||||
if (!rawScheme || !rest) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const isSrv = rawScheme.toLowerCase() === 'mongodb+srv';
|
||||
const delimiterMatch = /[/?#]/.exec(rest);
|
||||
const authority = delimiterMatch ? rest.slice(0, delimiterMatch.index) : rest;
|
||||
if (!authority) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const atIndex = authority.lastIndexOf('@');
|
||||
const hostList = atIndex >= 0 ? authority.slice(atIndex + 1) : authority;
|
||||
if (!hostList) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const segments = hostList.split(',');
|
||||
if (isSrv && segments.length !== 1) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return segments.every(segment => isValidMongoHostSegment(segment, !isSrv));
|
||||
}
|
||||
|
||||
const mongodbUriSchema = z.string().refine(isValidMongoUri, {
|
||||
message: 'Invalid MongoDB connection URI',
|
||||
});
|
||||
|
||||
// MongoDB configuration
|
||||
export const mongodbConfigSchema = z.object({
|
||||
enabled: z.boolean().default(true),
|
||||
uri: mongodbUriSchema, // URI is required and contains all connection info
|
||||
readUri: mongodbUriSchema.optional(), // Optional read-only URI (e.g. dev data-pipeline reading QA MongoDB)
|
||||
uri: z.string().url(), // URI is required and contains all connection info
|
||||
readUri: z.string().url().optional(), // Optional read-only URI (e.g. dev data-pipeline reading QA MongoDB)
|
||||
readOnly: z.boolean().default(false).optional(),
|
||||
database: z.string(), // Database name for reference
|
||||
poolSize: z.number().min(1).max(100).default(10),
|
||||
|
|
|
|||
|
|
@ -1,10 +1,19 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
|
||||
import * as loggerModule from '@stock-bot/logger';
|
||||
import { beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
|
||||
import { z } from 'zod';
|
||||
import { ConfigManager } from '../src/config-manager';
|
||||
import { ConfigError, ConfigValidationError } from '../src/errors';
|
||||
import type { ConfigLoader, Environment } from '../src/types';
|
||||
|
||||
// Mock the logger
|
||||
mock.module('@stock-bot/logger', () => ({
|
||||
getLogger: () => ({
|
||||
info: mock(() => {}),
|
||||
error: mock(() => {}),
|
||||
warn: mock(() => {}),
|
||||
debug: mock(() => {}),
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock loader class
|
||||
class MockLoader implements ConfigLoader {
|
||||
constructor(
|
||||
|
|
@ -19,28 +28,10 @@ class MockLoader implements ConfigLoader {
|
|||
|
||||
describe('ConfigManager', () => {
|
||||
let manager: ConfigManager<any>;
|
||||
let getLoggerSpy: ReturnType<typeof spyOn>;
|
||||
const originalNodeEnv = process.env.NODE_ENV;
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset environment
|
||||
delete process.env.NODE_ENV;
|
||||
getLoggerSpy = spyOn(loggerModule, 'getLogger').mockReturnValue({
|
||||
info: mock(() => {}),
|
||||
error: mock(() => {}),
|
||||
warn: mock(() => {}),
|
||||
debug: mock(() => {}),
|
||||
trace: mock(() => {}),
|
||||
} as any);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
getLoggerSpy?.mockRestore();
|
||||
if (originalNodeEnv === undefined) {
|
||||
delete process.env.NODE_ENV;
|
||||
} else {
|
||||
process.env.NODE_ENV = originalNodeEnv;
|
||||
}
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
|
|
|
|||
|
|
@ -1,12 +1,16 @@
|
|||
import * as fs from 'fs';
|
||||
import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test';
|
||||
import { readFileSync } from 'fs';
|
||||
import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
|
||||
import { ConfigLoaderError } from '../src/errors';
|
||||
import { EnvLoader } from '../src/loaders/env.loader';
|
||||
import { queueConfigSchema } from '../src/schemas';
|
||||
|
||||
// Mock fs module
|
||||
mock.module('fs', () => ({
|
||||
readFileSync: mock(() => ''),
|
||||
}));
|
||||
|
||||
describe('EnvLoader', () => {
|
||||
let loader: EnvLoader;
|
||||
let readFileSync: ReturnType<typeof spyOn>;
|
||||
const originalEnv = { ...process.env };
|
||||
|
||||
beforeEach(() => {
|
||||
|
|
@ -14,11 +18,9 @@ describe('EnvLoader', () => {
|
|||
for (const key in process.env) {
|
||||
delete process.env[key];
|
||||
}
|
||||
readFileSync = spyOn(fs, 'readFileSync').mockReturnValue('' as any);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
readFileSync?.mockRestore();
|
||||
// Restore original environment
|
||||
for (const key in process.env) {
|
||||
delete process.env[key];
|
||||
|
|
@ -369,20 +371,17 @@ KEY_WITHOUT_VALUE=
|
|||
|
||||
it('should warn on other file errors', () => {
|
||||
const consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {});
|
||||
try {
|
||||
(readFileSync as any).mockImplementation(() => {
|
||||
const error: any = new Error('Permission denied');
|
||||
error.code = 'EACCES';
|
||||
throw error;
|
||||
});
|
||||
|
||||
loader = new EnvLoader();
|
||||
loader.load();
|
||||
(readFileSync as any).mockImplementation(() => {
|
||||
const error: any = new Error('Permission denied');
|
||||
error.code = 'EACCES';
|
||||
throw error;
|
||||
});
|
||||
|
||||
expect(consoleWarnSpy).toHaveBeenCalled();
|
||||
} finally {
|
||||
consoleWarnSpy.mockRestore();
|
||||
}
|
||||
loader = new EnvLoader();
|
||||
loader.load();
|
||||
|
||||
expect(consoleWarnSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should try multiple env file paths', () => {
|
||||
|
|
|
|||
|
|
@ -1,23 +1,23 @@
|
|||
import * as fs from 'fs';
|
||||
import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test';
|
||||
import { existsSync, readFileSync } from 'fs';
|
||||
import { beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { ConfigLoaderError } from '../src/errors';
|
||||
import { FileLoader } from '../src/loaders/file.loader';
|
||||
|
||||
// Mock fs module
|
||||
mock.module('fs', () => ({
|
||||
existsSync: mock(() => false),
|
||||
readFileSync: mock(() => ''),
|
||||
}));
|
||||
|
||||
describe('FileLoader', () => {
|
||||
let loader: FileLoader;
|
||||
let existsSync: ReturnType<typeof spyOn>;
|
||||
let readFileSync: ReturnType<typeof spyOn>;
|
||||
const configPath = '/app/config';
|
||||
const environment = 'development';
|
||||
|
||||
beforeEach(() => {
|
||||
existsSync = spyOn(fs, 'existsSync').mockReturnValue(false);
|
||||
readFileSync = spyOn(fs, 'readFileSync').mockReturnValue('' as any);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
existsSync?.mockRestore();
|
||||
readFileSync?.mockRestore();
|
||||
// Reset mocks
|
||||
(existsSync as any).mockReset();
|
||||
(readFileSync as any).mockReset();
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
|
|
|
|||
|
|
@ -584,66 +584,10 @@ describe('Config Schemas', () => {
|
|||
expect(config).toEqual(input);
|
||||
});
|
||||
|
||||
it('should accept multi-host MongoDB seed lists for uri and readUri', () => {
|
||||
const config = mongodbConfigSchema.parse({
|
||||
uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin',
|
||||
readUri:
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017,[::1]:27018/stock?authSource=stock',
|
||||
database: 'stock_dev',
|
||||
});
|
||||
expect(config.uri).toBe(
|
||||
'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin'
|
||||
);
|
||||
expect(config.readUri).toBe(
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017,[::1]:27018/stock?authSource=stock'
|
||||
);
|
||||
});
|
||||
|
||||
it('should accept empty port spellings for mongodb:// in hostname and bracketed IPv6 forms', () => {
|
||||
const hostEmptyPort = mongodbConfigSchema.parse({
|
||||
uri: 'mongodb://mongo.prod.internal:/stock',
|
||||
readUri: 'mongodb://[::1]:/stock',
|
||||
database: 'stock',
|
||||
});
|
||||
expect(hostEmptyPort.uri).toBe('mongodb://mongo.prod.internal:/stock');
|
||||
expect(hostEmptyPort.readUri).toBe('mongodb://[::1]:/stock');
|
||||
|
||||
const seedListEmptyPort = mongodbConfigSchema.parse({
|
||||
uri: 'mongodb://u:p@mongo1.prod.internal:,[::1]:/stock',
|
||||
database: 'stock',
|
||||
});
|
||||
expect(seedListEmptyPort.uri).toBe('mongodb://u:p@mongo1.prod.internal:,[::1]:/stock');
|
||||
});
|
||||
|
||||
it('should validate URI format', () => {
|
||||
const invalidUris = [
|
||||
'invalid-uri',
|
||||
'http://localhost:27017/stock',
|
||||
'mongodb://',
|
||||
'mongodb://u:p@',
|
||||
'mongodb://u:p@localhost:27017,',
|
||||
'mongodb://u:p@:27017/stock',
|
||||
'mongodb://u:p@localhost:0/stock',
|
||||
'mongodb://u:p@localhost:99999/stock',
|
||||
'mongodb://u:p@[::1]:0/stock',
|
||||
'mongodb://u:p@[::1]:99999/stock',
|
||||
'mongodb://u:p@localhost:abc/stock',
|
||||
'mongodb+srv://u:p@localhost:/stock',
|
||||
'mongodb+srv://u:p@localhost:27017/stock',
|
||||
'mongodb+srv://u:p@host1.example.com,host2.example.com/stock',
|
||||
];
|
||||
for (const uri of invalidUris) {
|
||||
expect(() =>
|
||||
mongodbConfigSchema.parse({
|
||||
uri,
|
||||
database: 'testdb',
|
||||
})
|
||||
).toThrow();
|
||||
}
|
||||
expect(() =>
|
||||
mongodbConfigSchema.parse({
|
||||
uri: 'mongodb://localhost:27018/stock_dev',
|
||||
readUri: 'not-a-mongo-uri',
|
||||
uri: 'invalid-uri',
|
||||
database: 'testdb',
|
||||
})
|
||||
).toThrow();
|
||||
|
|
|
|||
|
|
@ -35,32 +35,14 @@ export type ContainerRegistrar = (
|
|||
) => void;
|
||||
|
||||
function extractMongoDatabaseFromUri(uri?: string): string | undefined {
|
||||
const trimmed = uri?.trim();
|
||||
if (!trimmed) {
|
||||
if (!uri) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const schemeMatch = /^mongodb(?:\+srv)?:\/\/(.*)$/i.exec(trimmed);
|
||||
const rest = schemeMatch?.[1];
|
||||
if (!rest) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const delimiterMatch = /[/?#]/.exec(rest);
|
||||
if (!delimiterMatch || delimiterMatch[0] !== '/') {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const pathPart = rest.slice(delimiterMatch.index).split(/[?#]/, 1)[0] ?? '';
|
||||
const rawDb = pathPart.replace(/^\/+/, '').split('/')[0];
|
||||
if (!rawDb) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
try {
|
||||
return decodeURIComponent(rawDb);
|
||||
const db = new URL(uri).pathname.replace(/^\/+/, '').split('/')[0];
|
||||
return db || undefined;
|
||||
} catch {
|
||||
return rawDb;
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -120,49 +120,6 @@ describe('ServiceContainerBuilder production configuration', () => {
|
|||
}
|
||||
});
|
||||
|
||||
it('extracts database from multi-host readUri when mongoReadOnly is enabled', async () => {
|
||||
const config = {
|
||||
...configuration(),
|
||||
database: {
|
||||
...configuration().database,
|
||||
mongodb: {
|
||||
enabled: true,
|
||||
uri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin',
|
||||
readUri:
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock?authSource=stock',
|
||||
database: 'stock_dev',
|
||||
},
|
||||
},
|
||||
};
|
||||
const container = await new ServiceContainerBuilder()
|
||||
.withConfig(config)
|
||||
.withOptions({
|
||||
enableMongoDB: true,
|
||||
mongoReadOnly: true,
|
||||
enablePostgres: false,
|
||||
enableQuestDB: false,
|
||||
enableCache: false,
|
||||
enableQueue: false,
|
||||
enableBrowser: false,
|
||||
enableProxy: false,
|
||||
})
|
||||
.skipInitialization()
|
||||
.build();
|
||||
|
||||
try {
|
||||
const resolvedConfig = container.resolve('config');
|
||||
expect(resolvedConfig.mongodb.readOnly).toBe(true);
|
||||
expect(resolvedConfig.mongodb.database).toBe('stock');
|
||||
|
||||
const mongo = container.resolve('mongoClient');
|
||||
expect(mongo).not.toBeNull();
|
||||
expect(mongo!.isReadOnly()).toBe(true);
|
||||
expect(mongo!.getDefaultDatabase()).toBe('stock');
|
||||
} finally {
|
||||
await container.dispose();
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects invalid settings and missing required app fields with schema errors', () => {
|
||||
expect(() =>
|
||||
new ServiceContainerBuilder().withConfig({
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { asFunction, createContainer, type AwilixContainer } from 'awilix';
|
||||
import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
|
||||
import { beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
|
||||
import type { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||
import * as logger from '@stock-bot/logger';
|
||||
import type { ExecutionContext, IHandler } from '@stock-bot/types';
|
||||
|
|
@ -55,7 +55,6 @@ describe('HandlerScanner', () => {
|
|||
let mockRegistry: HandlerRegistry;
|
||||
let container: AwilixContainer;
|
||||
let mockLogger: any;
|
||||
let getLoggerSpy: ReturnType<typeof spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create mock logger
|
||||
|
|
@ -64,11 +63,10 @@ describe('HandlerScanner', () => {
|
|||
debug: mock(() => {}),
|
||||
error: mock(() => {}),
|
||||
warn: mock(() => {}),
|
||||
trace: mock(() => {}),
|
||||
};
|
||||
|
||||
// Mock getLogger to return our mock logger
|
||||
getLoggerSpy = spyOn(logger, 'getLogger').mockReturnValue(mockLogger);
|
||||
spyOn(logger, 'getLogger').mockReturnValue(mockLogger);
|
||||
|
||||
// Create mock registry
|
||||
mockRegistry = {
|
||||
|
|
@ -89,10 +87,6 @@ describe('HandlerScanner', () => {
|
|||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
getLoggerSpy?.mockRestore();
|
||||
});
|
||||
|
||||
describe('scanHandlers', () => {
|
||||
it('should handle empty patterns gracefully', async () => {
|
||||
await scanner.scanHandlers([]);
|
||||
|
|
|
|||
|
|
@ -1,28 +1,21 @@
|
|||
import { asFunction, asValue, createContainer } from 'awilix';
|
||||
import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
|
||||
import * as queueModule from '@stock-bot/queue';
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import {
|
||||
registerApplicationServices,
|
||||
registerCacheServices,
|
||||
registerDatabaseServices,
|
||||
} from '../src/registrations';
|
||||
|
||||
// Mock the queue module
|
||||
mock.module('@stock-bot/queue', () => ({
|
||||
createServiceCache: mock(() => ({
|
||||
get: mock(() => Promise.resolve(null)),
|
||||
set: mock(() => Promise.resolve()),
|
||||
del: mock(() => Promise.resolve()),
|
||||
})),
|
||||
}));
|
||||
|
||||
describe('DI Registrations', () => {
|
||||
let createServiceCacheSpy: ReturnType<typeof spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
createServiceCacheSpy = spyOn(queueModule, 'createServiceCache').mockImplementation(
|
||||
(() => ({
|
||||
get: mock(() => Promise.resolve(null)),
|
||||
set: mock(() => Promise.resolve()),
|
||||
del: mock(() => Promise.resolve()),
|
||||
})) as any
|
||||
);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
createServiceCacheSpy?.mockRestore();
|
||||
});
|
||||
describe('registerCacheServices', () => {
|
||||
it('should register null cache when redis disabled', () => {
|
||||
const container = createContainer();
|
||||
|
|
@ -115,6 +108,22 @@ describe('DI Registrations', () => {
|
|||
it('should register MongoDB when config exists', () => {
|
||||
const container = createContainer();
|
||||
|
||||
// Mock MongoDB client
|
||||
const mockMongoClient = {
|
||||
connect: mock(() => Promise.resolve()),
|
||||
disconnect: mock(() => Promise.resolve()),
|
||||
getDb: mock(() => ({})),
|
||||
};
|
||||
|
||||
// Mock the MongoDB factory
|
||||
mock.module('@stock-bot/mongodb', () => ({
|
||||
MongoDBClient: class {
|
||||
constructor() {
|
||||
return mockMongoClient;
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
const config = {
|
||||
mongodb: {
|
||||
enabled: true,
|
||||
|
|
@ -131,6 +140,22 @@ describe('DI Registrations', () => {
|
|||
it('should register PostgreSQL when config exists', () => {
|
||||
const container = createContainer();
|
||||
|
||||
// Mock Postgres client
|
||||
const mockPostgresClient = {
|
||||
connect: mock(() => Promise.resolve()),
|
||||
disconnect: mock(() => Promise.resolve()),
|
||||
query: mock(() => Promise.resolve({ rows: [] })),
|
||||
};
|
||||
|
||||
// Mock the Postgres factory
|
||||
mock.module('@stock-bot/postgres', () => ({
|
||||
PostgresClient: class {
|
||||
constructor() {
|
||||
return mockPostgresClient;
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
const config = {
|
||||
postgres: {
|
||||
enabled: true,
|
||||
|
|
@ -150,6 +175,22 @@ describe('DI Registrations', () => {
|
|||
it('should register QuestDB when config exists', () => {
|
||||
const container = createContainer();
|
||||
|
||||
// Mock QuestDB client
|
||||
const mockQuestdbClient = {
|
||||
connect: mock(() => Promise.resolve()),
|
||||
disconnect: mock(() => Promise.resolve()),
|
||||
query: mock(() => Promise.resolve({ data: [] })),
|
||||
};
|
||||
|
||||
// Mock the QuestDB factory
|
||||
mock.module('@stock-bot/questdb', () => ({
|
||||
QuestDBClient: class {
|
||||
constructor() {
|
||||
return mockQuestdbClient;
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
const config = {
|
||||
questdb: {
|
||||
enabled: true,
|
||||
|
|
@ -240,6 +281,21 @@ describe('DI Registrations', () => {
|
|||
}),
|
||||
});
|
||||
|
||||
// Mock queue manager
|
||||
const mockQueueManager = {
|
||||
getQueue: mock(() => ({})),
|
||||
startAllWorkers: mock(() => {}),
|
||||
shutdown: mock(() => Promise.resolve()),
|
||||
};
|
||||
|
||||
mock.module('@stock-bot/queue', () => ({
|
||||
QueueManager: class {
|
||||
constructor() {
|
||||
return mockQueueManager;
|
||||
}
|
||||
},
|
||||
}));
|
||||
|
||||
const config = {
|
||||
service: {
|
||||
name: 'test-service',
|
||||
|
|
|
|||
|
|
@ -1,23 +1,25 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
|
||||
import { afterEach, describe, expect, it, mock } from 'bun:test';
|
||||
import type { BaseAppConfig } from '@stock-bot/config';
|
||||
import * as loggerModule from '@stock-bot/logger';
|
||||
import { Shutdown } from '@stock-bot/shutdown';
|
||||
import { ServiceApplication } from '../src/service-application';
|
||||
import type { ServiceApplicationConfig, ServiceLifecycleHooks } from '../src/service-application';
|
||||
|
||||
// Mock logger object used via spyOn in beforeEach (restored in afterEach)
|
||||
const mockLogger: any = {
|
||||
// Mock logger module
|
||||
const mockLogger = {
|
||||
info: mock(() => {}),
|
||||
error: mock(() => {}),
|
||||
warn: mock(() => {}),
|
||||
debug: mock(() => {}),
|
||||
trace: mock(() => {}),
|
||||
child: mock(() => mockLogger),
|
||||
};
|
||||
mockLogger.child = mock(() => mockLogger);
|
||||
|
||||
// Mock shutdown instance used via spyOn(Shutdown, 'getInstance') in beforeEach
|
||||
mock.module('@stock-bot/logger', () => ({
|
||||
getLogger: () => mockLogger,
|
||||
setLoggerConfig: mock(() => {}),
|
||||
shutdownLoggers: mock(() => Promise.resolve()),
|
||||
}));
|
||||
|
||||
// Mock shutdown module
|
||||
const mockShutdownInstance = {
|
||||
shutdown: mock(() => Promise.resolve()),
|
||||
onShutdown: mock(() => {}),
|
||||
onShutdownHigh: mock(() => {}),
|
||||
onShutdownMedium: mock(() => {}),
|
||||
|
|
@ -28,13 +30,24 @@ const mockShutdownInstance = {
|
|||
executeCallbacks: mock(() => Promise.resolve()),
|
||||
};
|
||||
|
||||
// Mock server returned by spyOn(Bun, 'serve')
|
||||
const mockShutdown = {
|
||||
getInstance: mock(() => mockShutdownInstance),
|
||||
};
|
||||
|
||||
mock.module('@stock-bot/shutdown', () => ({
|
||||
Shutdown: mockShutdown,
|
||||
}));
|
||||
|
||||
// Mock Bun.serve
|
||||
const mockServer = {
|
||||
stop: mock(() => {}),
|
||||
port: 3000,
|
||||
hostname: '0.0.0.0',
|
||||
};
|
||||
|
||||
const _originalBunServe = Bun.serve;
|
||||
Bun.serve = mock(() => mockServer);
|
||||
|
||||
const mockConfig: BaseAppConfig = {
|
||||
name: 'test-service',
|
||||
version: '1.0.0',
|
||||
|
|
@ -62,44 +75,13 @@ const mockConfig: BaseAppConfig = {
|
|||
|
||||
describe('ServiceApplication', () => {
|
||||
let app: ServiceApplication;
|
||||
let getLoggerSpy: ReturnType<typeof spyOn>;
|
||||
let setLoggerConfigSpy: ReturnType<typeof spyOn>;
|
||||
let shutdownLoggersSpy: ReturnType<typeof spyOn>;
|
||||
let shutdownGetInstanceSpy: ReturnType<typeof spyOn>;
|
||||
let bunServeSpy: ReturnType<typeof spyOn>;
|
||||
|
||||
beforeEach(() => {
|
||||
getLoggerSpy = spyOn(loggerModule, 'getLogger').mockReturnValue(mockLogger);
|
||||
setLoggerConfigSpy = spyOn(loggerModule, 'setLoggerConfig').mockImplementation(() => {});
|
||||
shutdownLoggersSpy = spyOn(loggerModule, 'shutdownLoggers').mockResolvedValue(undefined);
|
||||
shutdownGetInstanceSpy = spyOn(Shutdown, 'getInstance').mockReturnValue(
|
||||
mockShutdownInstance as any
|
||||
);
|
||||
bunServeSpy = spyOn(Bun, 'serve').mockImplementation((() => mockServer) as any);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Clean up app if it exists before restoring spies
|
||||
if (app) {
|
||||
app.stop().catch(() => {});
|
||||
app = null as any;
|
||||
}
|
||||
|
||||
// Restore module/global spies so no state leaks to other test files
|
||||
getLoggerSpy?.mockRestore();
|
||||
setLoggerConfigSpy?.mockRestore();
|
||||
shutdownLoggersSpy?.mockRestore();
|
||||
shutdownGetInstanceSpy?.mockRestore();
|
||||
bunServeSpy?.mockRestore();
|
||||
|
||||
// Reset mocks
|
||||
mockLogger.info.mockReset();
|
||||
mockLogger.error.mockReset();
|
||||
mockLogger.warn.mockReset();
|
||||
mockLogger.debug.mockReset();
|
||||
mockLogger.trace.mockReset();
|
||||
mockShutdownInstance.shutdown.mockReset();
|
||||
mockShutdownInstance.shutdown.mockImplementation(() => Promise.resolve());
|
||||
mockShutdownInstance.onShutdown.mockReset();
|
||||
mockShutdownInstance.onShutdownHigh.mockReset();
|
||||
mockShutdownInstance.onShutdownMedium.mockReset();
|
||||
|
|
@ -108,6 +90,12 @@ describe('ServiceApplication', () => {
|
|||
mockShutdownInstance.registerAsync.mockReset();
|
||||
mockShutdownInstance.handleTermination.mockReset();
|
||||
mockShutdownInstance.executeCallbacks.mockReset();
|
||||
|
||||
// Clean up app if it exists
|
||||
if (app) {
|
||||
app.stop().catch(() => {});
|
||||
app = null as any;
|
||||
}
|
||||
});
|
||||
|
||||
describe('constructor', () => {
|
||||
|
|
@ -148,7 +136,7 @@ describe('ServiceApplication', () => {
|
|||
};
|
||||
|
||||
app = new ServiceApplication(mockConfig, serviceConfig);
|
||||
expect(shutdownGetInstanceSpy).toHaveBeenCalledWith({
|
||||
expect(mockShutdown.getInstance).toHaveBeenCalledWith({
|
||||
timeout: 30000,
|
||||
});
|
||||
});
|
||||
|
|
@ -617,14 +605,19 @@ describe('ServiceApplication', () => {
|
|||
|
||||
describe('stop method', () => {
|
||||
it('should trigger shutdown', async () => {
|
||||
const localShutdownInstance = {
|
||||
const mockShutdownInstance = {
|
||||
shutdown: mock(() => Promise.resolve()),
|
||||
onShutdown: mock(() => {}),
|
||||
onShutdownHigh: mock(() => {}),
|
||||
onShutdownMedium: mock(() => {}),
|
||||
onShutdownLow: mock(() => {}),
|
||||
};
|
||||
shutdownGetInstanceSpy.mockReturnValue(localShutdownInstance as any);
|
||||
|
||||
mock.module('@stock-bot/shutdown', () => ({
|
||||
Shutdown: {
|
||||
getInstance: () => mockShutdownInstance,
|
||||
},
|
||||
}));
|
||||
|
||||
const serviceConfig: ServiceApplicationConfig = {
|
||||
serviceName: 'test-service',
|
||||
|
|
@ -634,7 +627,7 @@ describe('ServiceApplication', () => {
|
|||
|
||||
await app.stop();
|
||||
|
||||
expect(localShutdownInstance.shutdown).toHaveBeenCalled();
|
||||
expect(mockShutdownInstance.shutdown).toHaveBeenCalled();
|
||||
expect(mockLogger.info).toHaveBeenCalledWith('Stopping test-service service...');
|
||||
});
|
||||
});
|
||||
|
|
@ -672,14 +665,19 @@ describe('ServiceApplication', () => {
|
|||
|
||||
describe('shutdown handlers', () => {
|
||||
it('should register all shutdown handlers during start', async () => {
|
||||
const localShutdownInstance = {
|
||||
const mockShutdownInstance = {
|
||||
shutdown: mock(() => Promise.resolve()),
|
||||
onShutdown: mock(() => {}),
|
||||
onShutdownHigh: mock(() => {}),
|
||||
onShutdownMedium: mock(() => {}),
|
||||
onShutdownLow: mock(() => {}),
|
||||
};
|
||||
shutdownGetInstanceSpy.mockReturnValue(localShutdownInstance as any);
|
||||
|
||||
mock.module('@stock-bot/shutdown', () => ({
|
||||
Shutdown: {
|
||||
getInstance: () => mockShutdownInstance,
|
||||
},
|
||||
}));
|
||||
|
||||
const serviceConfig: ServiceApplicationConfig = {
|
||||
serviceName: 'test-service',
|
||||
|
|
@ -733,10 +731,10 @@ describe('ServiceApplication', () => {
|
|||
);
|
||||
|
||||
// Should have registered shutdown handlers
|
||||
expect(localShutdownInstance.onShutdown).toHaveBeenCalledTimes(5); // Queue, HTTP, Custom, Services, Loggers
|
||||
expect(mockShutdownInstance.onShutdown).toHaveBeenCalledTimes(5); // Queue, HTTP, Custom, Services, Loggers
|
||||
|
||||
// Test the handlers by calling them
|
||||
const shutdownHandlers = (localShutdownInstance.onShutdown as any).mock.calls;
|
||||
const shutdownHandlers = (mockShutdownInstance.onShutdown as any).mock.calls;
|
||||
|
||||
// Find and execute queue shutdown handler (priority 9)
|
||||
const queueHandler = shutdownHandlers.find(call => call[2] === 'Queue System');
|
||||
|
|
|
|||
|
|
@ -96,20 +96,14 @@ describe('createJobHandler', () => {
|
|||
});
|
||||
|
||||
it('should support async operations', async () => {
|
||||
// Gate created before the wrapper runs, so the test does not assume synchronous invocation.
|
||||
let releaseAsyncWork!: () => void;
|
||||
const asyncWorkGate = new Promise<void>(resolve => {
|
||||
releaseAsyncWork = resolve;
|
||||
});
|
||||
let callbackFinished = false;
|
||||
|
||||
const handler = createJobHandler<TestPayload, TestResult>(async job => {
|
||||
await asyncWorkGate;
|
||||
callbackFinished = true;
|
||||
// Simulate async operation
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
return {
|
||||
success: true,
|
||||
processedBy: job.data.userId,
|
||||
timestamp: new Date(0),
|
||||
timestamp: new Date(),
|
||||
};
|
||||
});
|
||||
|
||||
|
|
@ -126,22 +120,12 @@ describe('createJobHandler', () => {
|
|||
updateProgress: async () => {},
|
||||
};
|
||||
|
||||
let wrapperSettled = false;
|
||||
const resultPromise = handler(mockJob as any).finally(() => {
|
||||
wrapperSettled = true;
|
||||
});
|
||||
const startTime = Date.now();
|
||||
const result = await handler(mockJob as any);
|
||||
const endTime = Date.now();
|
||||
|
||||
// Drain microtasks: the wrapper must still be waiting on the callback.
|
||||
await Promise.resolve();
|
||||
await Promise.resolve();
|
||||
expect(wrapperSettled).toBe(false);
|
||||
expect(callbackFinished).toBe(false);
|
||||
|
||||
releaseAsyncWork();
|
||||
const result = await resultPromise;
|
||||
|
||||
expect(callbackFinished).toBe(true);
|
||||
expect(result).toEqual({ success: true, processedBy: 'user-789', timestamp: new Date(0) });
|
||||
expect(result.success).toBe(true);
|
||||
expect(endTime - startTime).toBeGreaterThanOrEqual(10);
|
||||
});
|
||||
|
||||
it('should maintain type safety for complex payloads', () => {
|
||||
|
|
|
|||
|
|
@ -99,14 +99,6 @@ export class QueueManager {
|
|||
this.ioredisConnection = deps?.createRedis
|
||||
? deps.createRedis(ioredisOptions)
|
||||
: new Redis(ioredisOptions);
|
||||
if (typeof this.ioredisConnection.on === 'function') {
|
||||
this.ioredisConnection.on('error', error => {
|
||||
this.logger.error('QueueManager Redis connection error', {
|
||||
service: this.serviceName,
|
||||
error,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Rate limiter will be initialized when rules are added dynamically
|
||||
// No longer initialized from config
|
||||
|
|
|
|||
|
|
@ -123,7 +123,7 @@ export class Queue {
|
|||
|
||||
// Initialize queue events if workers will be used
|
||||
if (config.workers && config.workers > 0) {
|
||||
this.queueEvents = this.createQueueEvents(connection);
|
||||
this.queueEvents = new QueueEvents(queueName, { connection });
|
||||
}
|
||||
|
||||
// Start workers if requested and not explicitly disabled
|
||||
|
|
@ -262,18 +262,12 @@ export class Queue {
|
|||
return await this.bullQueue.getJob(jobId);
|
||||
}
|
||||
|
||||
private createQueueEvents(connection: ReturnType<typeof getRedisConnection>): QueueEvents {
|
||||
const queueEvents = new QueueEvents(this.queueName, { connection });
|
||||
queueEvents.on('error', error =>
|
||||
this.logger.error('QueueEvents connection error', { queueName: this.queueName, error })
|
||||
);
|
||||
return queueEvents;
|
||||
}
|
||||
|
||||
/** Wait for a result using a QueueEvents connection owned by this queue. */
|
||||
async waitForJob<T>(job: Job<unknown, T>, timeout = 30000): Promise<T> {
|
||||
if (!this.queueEvents) {
|
||||
this.queueEvents = this.createQueueEvents(getRedisConnection(this.redisConfig));
|
||||
this.queueEvents = new QueueEvents(this.queueName, {
|
||||
connection: getRedisConnection(this.redisConfig),
|
||||
});
|
||||
}
|
||||
await this.queueEvents.waitUntilReady();
|
||||
return job.waitUntilFinished(this.queueEvents, timeout);
|
||||
|
|
@ -595,7 +589,7 @@ export class Queue {
|
|||
// Initialize queue events if not already done
|
||||
if (!this.queueEvents) {
|
||||
const connection = getRedisConnection(this.redisConfig);
|
||||
this.queueEvents = this.createQueueEvents(connection);
|
||||
this.queueEvents = new QueueEvents(this.queueName, { connection });
|
||||
}
|
||||
|
||||
this.startWorkers(workerCount, concurrency);
|
||||
|
|
|
|||
|
|
@ -1,37 +1,17 @@
|
|||
import { afterEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import { Queue, removeScheduledJobsFromBullQueue } from '../src/queue';
|
||||
import { QueueManager } from '../src/queue-manager';
|
||||
import type { QueueWorkerConfig, RedisConfig } from '../src/types';
|
||||
|
||||
describe('Queue Class', () => {
|
||||
// Use a non-QA isolated loopback port so unit tests never touch QA Dragonfly (localhost:6379)
|
||||
const mockRedisConfig: RedisConfig = {
|
||||
host: '127.0.0.1',
|
||||
port: 16379,
|
||||
maxRetriesPerRequest: 1,
|
||||
retryDelay: 50,
|
||||
host: 'localhost',
|
||||
port: 6379,
|
||||
};
|
||||
const createdQueues: Queue[] = [];
|
||||
|
||||
function trackQueue(queue: Queue): Queue {
|
||||
createdQueues.push(queue);
|
||||
return queue;
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
createdQueues.splice(0).map(async queue => {
|
||||
// Stop reconnect timers on unreachable test sockets before awaiting BullMQ close()
|
||||
(queue.getBullQueue() as any).connection?._client?.disconnect(false);
|
||||
(queue as any).queueEvents?.connection?._client?.disconnect(false);
|
||||
await queue.close().catch(() => {});
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
describe('basic functionality', () => {
|
||||
it('should create queue with minimal config', () => {
|
||||
const queue = trackQueue(new Queue('test-queue', mockRedisConfig));
|
||||
const queue = new Queue('test-queue', mockRedisConfig);
|
||||
expect(queue).toBeDefined();
|
||||
expect(queue.getName()).toBe('test-queue');
|
||||
});
|
||||
|
|
@ -42,7 +22,7 @@ describe('Queue Class', () => {
|
|||
backoff: { type: 'exponential' as const, delay: 2000 },
|
||||
};
|
||||
|
||||
const queue = trackQueue(new Queue('test-queue', mockRedisConfig, defaultJobOptions));
|
||||
const queue = new Queue('test-queue', mockRedisConfig, defaultJobOptions);
|
||||
expect(queue).toBeDefined();
|
||||
expect(queue.getName()).toBe('test-queue');
|
||||
});
|
||||
|
|
@ -56,7 +36,7 @@ describe('Queue Class', () => {
|
|||
trace: mock(() => {}),
|
||||
};
|
||||
|
||||
const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger));
|
||||
const queue = new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger);
|
||||
expect(queue).toBeDefined();
|
||||
});
|
||||
|
||||
|
|
@ -68,19 +48,19 @@ describe('Queue Class', () => {
|
|||
serviceName: 'test-service',
|
||||
};
|
||||
|
||||
const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, workerConfig));
|
||||
const queue = new Queue('test-queue', mockRedisConfig, {}, workerConfig);
|
||||
expect(queue).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('queue naming and utilities', () => {
|
||||
it('should return queue name', () => {
|
||||
const queue = trackQueue(new Queue('my-test-queue', mockRedisConfig));
|
||||
const queue = new Queue('my-test-queue', mockRedisConfig);
|
||||
expect(queue.getName()).toBe('my-test-queue');
|
||||
});
|
||||
|
||||
it('should get bull queue instance', () => {
|
||||
const queue = trackQueue(new Queue('test-queue', mockRedisConfig));
|
||||
const queue = new Queue('test-queue', mockRedisConfig);
|
||||
const bullQueue = queue.getBullQueue();
|
||||
expect(bullQueue).toBeDefined();
|
||||
});
|
||||
|
|
@ -103,7 +83,7 @@ describe('Queue Class', () => {
|
|||
child: mock(() => mockChildLogger),
|
||||
};
|
||||
|
||||
const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger));
|
||||
const queue = new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger);
|
||||
const childLogger = queue.createChildLogger('batch', { batchId: '123' });
|
||||
|
||||
expect(childLogger).toBe(mockChildLogger);
|
||||
|
|
@ -119,7 +99,7 @@ describe('Queue Class', () => {
|
|||
trace: mock(() => {}),
|
||||
};
|
||||
|
||||
const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger));
|
||||
const queue = new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger);
|
||||
const childLogger = queue.createChildLogger('batch', { batchId: '123' });
|
||||
|
||||
expect(childLogger).toBe(mockLogger);
|
||||
|
|
@ -128,7 +108,7 @@ describe('Queue Class', () => {
|
|||
|
||||
describe('worker count methods', () => {
|
||||
it('should get worker count when no workers', () => {
|
||||
const queue = trackQueue(new Queue('test-queue', mockRedisConfig));
|
||||
const queue = new Queue('test-queue', mockRedisConfig);
|
||||
expect(queue.getWorkerCount()).toBe(0);
|
||||
});
|
||||
|
||||
|
|
@ -138,7 +118,7 @@ describe('Queue Class', () => {
|
|||
startWorker: false, // Don't actually start
|
||||
};
|
||||
|
||||
const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, workerConfig));
|
||||
const queue = new Queue('test-queue', mockRedisConfig, {}, workerConfig);
|
||||
// Workers aren't actually started with startWorker: false
|
||||
expect(queue.getWorkerCount()).toBe(0);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,122 +0,0 @@
|
|||
import { EventEmitter } from 'events';
|
||||
import { afterEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { Queue } from '../src/queue';
|
||||
import { QueueManager } from '../src/queue-manager';
|
||||
import type { RedisConfig } from '../src/types';
|
||||
|
||||
// Regression: an EventEmitter that emits 'error' with no listener throws synchronously,
|
||||
// so an unreachable Redis used to surface as an unhandled error mid-suite.
|
||||
// Non-QA loopback port; nothing is expected to listen here.
|
||||
const unreachableRedis: RedisConfig = {
|
||||
host: '127.0.0.1',
|
||||
port: 16379,
|
||||
maxRetriesPerRequest: 1,
|
||||
retryDelay: 50,
|
||||
};
|
||||
|
||||
function createLogger() {
|
||||
return {
|
||||
info: mock(() => {}),
|
||||
error: mock(() => {}),
|
||||
warn: mock(() => {}),
|
||||
debug: mock(() => {}),
|
||||
trace: mock(() => {}),
|
||||
};
|
||||
}
|
||||
|
||||
describe('Queue connection error handling', () => {
|
||||
const queues: Queue[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
queues.splice(0).map(async queue => {
|
||||
// Stop reconnect timers on the unreachable socket before awaiting close()
|
||||
(queue.getBullQueue() as any).connection?._client?.disconnect(false);
|
||||
(queue as any).queueEvents?.connection?._client?.disconnect(false);
|
||||
await queue.close().catch(() => {});
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('logs QueueEvents connection errors instead of throwing', () => {
|
||||
const logger = createLogger();
|
||||
const queue = new Queue(
|
||||
'conn-error-queue',
|
||||
unreachableRedis,
|
||||
{},
|
||||
{ workers: 1, startWorker: false },
|
||||
logger as any
|
||||
);
|
||||
queues.push(queue);
|
||||
const queueEvents = (queue as any).queueEvents as EventEmitter;
|
||||
expect(queueEvents).toBeDefined();
|
||||
expect(queueEvents.listenerCount('error')).toBeGreaterThanOrEqual(1);
|
||||
|
||||
const failure = new Error('connect ECONNREFUSED 127.0.0.1:16379');
|
||||
expect(() => queueEvents.emit('error', failure)).not.toThrow();
|
||||
|
||||
expect(logger.error).toHaveBeenCalledWith('QueueEvents connection error', {
|
||||
queueName: 'conn-error-queue',
|
||||
error: failure,
|
||||
});
|
||||
});
|
||||
|
||||
it('does not create QueueEvents for a producer-only queue', () => {
|
||||
const queue = new Queue('producer-only', unreachableRedis, {}, {}, createLogger() as any);
|
||||
queues.push(queue);
|
||||
|
||||
expect((queue as any).queueEvents).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('QueueManager connection error handling', () => {
|
||||
function createFakeRedis() {
|
||||
const redis = new EventEmitter() as EventEmitter & {
|
||||
quit: ReturnType<typeof mock>;
|
||||
disconnect: ReturnType<typeof mock>;
|
||||
};
|
||||
redis.quit = mock(async () => 'OK');
|
||||
redis.disconnect = mock(() => {});
|
||||
return redis;
|
||||
}
|
||||
|
||||
it('logs rate-limiter Redis errors instead of throwing', async () => {
|
||||
const logger = createLogger();
|
||||
const redis = createFakeRedis();
|
||||
const manager = new QueueManager(
|
||||
{ serviceName: 'conn-error-svc', redis: unreachableRedis },
|
||||
undefined,
|
||||
logger as any,
|
||||
{ createRedis: () => redis as any }
|
||||
);
|
||||
|
||||
try {
|
||||
expect(redis.listenerCount('error')).toBe(1);
|
||||
const failure = new Error('connect ECONNREFUSED 127.0.0.1:16379');
|
||||
|
||||
expect(() => redis.emit('error', failure)).not.toThrow();
|
||||
|
||||
expect(logger.error).toHaveBeenCalledWith('QueueManager Redis connection error', {
|
||||
service: 'conn-error-svc',
|
||||
error: failure,
|
||||
});
|
||||
} finally {
|
||||
await manager.shutdown();
|
||||
}
|
||||
expect(redis.quit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('accepts an injected Redis client without an event API', async () => {
|
||||
const quit = mock(async () => 'OK');
|
||||
const manager = new QueueManager(
|
||||
{ serviceName: 'no-events-svc', redis: unreachableRedis },
|
||||
undefined,
|
||||
createLogger() as any,
|
||||
{ createRedis: () => ({ quit, disconnect: mock(() => {}) }) as any }
|
||||
);
|
||||
|
||||
await manager.shutdown();
|
||||
|
||||
expect(quit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,4 +1,4 @@
|
|||
import { afterEach, describe, expect, it } from 'bun:test';
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { createServiceCache, ServiceCache } from '../src/service-cache';
|
||||
import {
|
||||
generateCachePrefix,
|
||||
|
|
@ -78,40 +78,39 @@ describe('Service Utilities', () => {
|
|||
});
|
||||
|
||||
describe('ServiceCache', () => {
|
||||
// Use a non-QA isolated loopback port and non-shared clients so unit tests never touch QA Dragonfly (localhost:6379)
|
||||
const mockRedisConfig = {
|
||||
host: '127.0.0.1',
|
||||
port: 16379,
|
||||
maxRetriesPerRequest: 1,
|
||||
retryDelay: 50,
|
||||
};
|
||||
const createdCaches: ServiceCache[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(createdCaches.splice(0).map(cache => cache.disconnect().catch(() => {})));
|
||||
});
|
||||
|
||||
it('should create service cache', () => {
|
||||
const serviceCache = createServiceCache('myservice', mockRedisConfig, { shared: false });
|
||||
createdCaches.push(serviceCache);
|
||||
const mockRedisConfig = {
|
||||
host: 'localhost',
|
||||
port: 6379,
|
||||
};
|
||||
|
||||
// Since ServiceCache constructor internally creates a real cache,
|
||||
// we can't easily test it without mocking the createCache function
|
||||
// For now, just test that the function exists and returns something
|
||||
const serviceCache = createServiceCache('myservice', mockRedisConfig);
|
||||
expect(serviceCache).toBeDefined();
|
||||
expect(serviceCache).toBeInstanceOf(ServiceCache);
|
||||
});
|
||||
|
||||
it('should handle cache prefix correctly', () => {
|
||||
const serviceCache = createServiceCache('webApi', mockRedisConfig, { shared: false });
|
||||
createdCaches.push(serviceCache);
|
||||
const mockRedisConfig = {
|
||||
host: 'localhost',
|
||||
port: 6379,
|
||||
};
|
||||
|
||||
const serviceCache = createServiceCache('webApi', mockRedisConfig);
|
||||
expect(serviceCache).toBeDefined();
|
||||
// The prefix is set internally as cache:web-api
|
||||
expect(serviceCache.getKey('test')).toBe('cache:web-api:test');
|
||||
});
|
||||
|
||||
it('should support global cache option', () => {
|
||||
const globalCache = createServiceCache('myservice', mockRedisConfig, {
|
||||
global: true,
|
||||
shared: false,
|
||||
});
|
||||
createdCaches.push(globalCache);
|
||||
const mockRedisConfig = {
|
||||
host: 'localhost',
|
||||
port: 6379,
|
||||
};
|
||||
|
||||
const globalCache = createServiceCache('myservice', mockRedisConfig, { global: true });
|
||||
expect(globalCache).toBeDefined();
|
||||
// Global cache uses a different prefix
|
||||
expect(globalCache.getKey('test')).toBe('stock-bot:shared:test');
|
||||
|
|
@ -121,16 +120,16 @@ describe('ServiceCache', () => {
|
|||
describe('Batch Processing', () => {
|
||||
it('should handle batch job data types', () => {
|
||||
const batchJob: BatchJobData = {
|
||||
payloadKey: 'batch:payload:1',
|
||||
batchIndex: 0,
|
||||
totalBatches: 3,
|
||||
itemCount: 10,
|
||||
totalDelayHours: 1,
|
||||
items: [1, 2, 3],
|
||||
options: {
|
||||
batchSize: 10,
|
||||
concurrency: 2,
|
||||
},
|
||||
};
|
||||
|
||||
expect(batchJob.payloadKey).toBe('batch:payload:1');
|
||||
expect(batchJob.totalBatches).toBe(3);
|
||||
expect(batchJob.itemCount).toBe(10);
|
||||
expect(batchJob.items).toHaveLength(3);
|
||||
expect(batchJob.options.batchSize).toBe(10);
|
||||
expect(batchJob.options.concurrency).toBe(2);
|
||||
});
|
||||
|
||||
it('should process batch results', () => {
|
||||
|
|
|
|||
|
|
@ -15,7 +15,6 @@ export class Shutdown {
|
|||
private shutdownTimeout: number;
|
||||
private callbacks: CallbackEntry[] = [];
|
||||
private signalHandlersRegistered = false;
|
||||
private registeredSignalHandlers = new Map<NodeJS.Signals, () => void>();
|
||||
private shutdownPromise: Promise<void> | null = null;
|
||||
private triggerSignal: string | null = null;
|
||||
|
||||
|
|
@ -34,37 +33,6 @@ export class Shutdown {
|
|||
return Shutdown.instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* Dispose the singleton instance and remove its signal listeners.
|
||||
*/
|
||||
static reset(): void {
|
||||
if (Shutdown.instance) {
|
||||
Shutdown.instance.dispose();
|
||||
Shutdown.instance = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove process signal handlers registered by this instance.
|
||||
*/
|
||||
removeSignalHandlers(): void {
|
||||
for (const [signal, listener] of this.registeredSignalHandlers) {
|
||||
process.off(signal, listener);
|
||||
}
|
||||
this.registeredSignalHandlers.clear();
|
||||
this.signalHandlersRegistered = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up signal listeners and clear singleton reference if this is the active singleton.
|
||||
*/
|
||||
dispose(): void {
|
||||
this.removeSignalHandlers();
|
||||
if (Shutdown.instance === this) {
|
||||
Shutdown.instance = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get current shutdown status
|
||||
*/
|
||||
|
|
@ -185,7 +153,7 @@ export class Shutdown {
|
|||
|
||||
signals.forEach(signal => {
|
||||
// Use process.on instead of process.once to handle multiple signals
|
||||
const listener = async () => {
|
||||
process.on(signal, async () => {
|
||||
this.logger.info(`Received ${signal} signal`);
|
||||
|
||||
// If already shutting down, ignore the signal
|
||||
|
|
@ -210,10 +178,7 @@ export class Shutdown {
|
|||
|
||||
process.exit(1);
|
||||
}
|
||||
};
|
||||
|
||||
this.registeredSignalHandlers.set(signal, listener);
|
||||
process.on(signal, listener);
|
||||
});
|
||||
|
||||
this.logger.debug(`Registered handler for ${signal}`);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,15 +6,14 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
|
||||
beforeEach(() => {
|
||||
// Reset singleton instance for each test
|
||||
Shutdown.reset();
|
||||
(Shutdown as any).instance = null;
|
||||
// Create a fresh instance for each test
|
||||
shutdownInstance = new Shutdown({ autoRegister: false });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Clean up singleton and any signal listeners
|
||||
shutdownInstance?.dispose();
|
||||
Shutdown.reset();
|
||||
// Clean up singleton
|
||||
(Shutdown as any).instance = null;
|
||||
});
|
||||
|
||||
describe('Basic Functionality', () => {
|
||||
|
|
@ -251,18 +250,10 @@ describe('Shutdown Comprehensive Tests', () => {
|
|||
});
|
||||
|
||||
it('should use default timeout', () => {
|
||||
const defaultShutdown = new Shutdown();
|
||||
let secondShutdown: Shutdown | undefined;
|
||||
const _defaultShutdown = new Shutdown();
|
||||
|
||||
try {
|
||||
// Can't directly test timeout value, but we can verify it doesn't throw
|
||||
expect(() => {
|
||||
secondShutdown = new Shutdown();
|
||||
}).not.toThrow();
|
||||
} finally {
|
||||
defaultShutdown.dispose();
|
||||
secondShutdown?.dispose();
|
||||
}
|
||||
// Can't directly test timeout value, but we can verify it doesn't throw
|
||||
expect(() => new Shutdown()).not.toThrow();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,136 +0,0 @@
|
|||
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
|
||||
import { Shutdown } from '../src/shutdown';
|
||||
|
||||
// These tests use the real `process` listener registry (no stubs) because the
|
||||
// regression being guarded is listeners leaking across test files in one bun process.
|
||||
const SIGNALS = ['SIGTERM', 'SIGINT'] as const;
|
||||
|
||||
function listenerCounts(): Record<(typeof SIGNALS)[number], number> {
|
||||
return {
|
||||
SIGTERM: process.listenerCount('SIGTERM'),
|
||||
SIGINT: process.listenerCount('SIGINT'),
|
||||
};
|
||||
}
|
||||
|
||||
describe('Shutdown signal listener cleanup', () => {
|
||||
const created: Shutdown[] = [];
|
||||
let baseline: ReturnType<typeof listenerCounts>;
|
||||
|
||||
function track(instance: Shutdown): Shutdown {
|
||||
created.push(instance);
|
||||
return instance;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
Shutdown.reset();
|
||||
baseline = listenerCounts();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
for (const instance of created.splice(0)) {
|
||||
instance.dispose();
|
||||
}
|
||||
Shutdown.reset();
|
||||
});
|
||||
|
||||
it('autoRegister adds exactly one SIGTERM and one SIGINT listener and dispose removes them', () => {
|
||||
const shutdown = track(new Shutdown());
|
||||
|
||||
expect(listenerCounts()).toEqual({
|
||||
SIGTERM: baseline.SIGTERM + 1,
|
||||
SIGINT: baseline.SIGINT + 1,
|
||||
});
|
||||
|
||||
shutdown.dispose();
|
||||
|
||||
expect(listenerCounts()).toEqual(baseline);
|
||||
});
|
||||
|
||||
it('autoRegister: false adds no process listeners', () => {
|
||||
track(new Shutdown({ autoRegister: false }));
|
||||
|
||||
expect(listenerCounts()).toEqual(baseline);
|
||||
});
|
||||
|
||||
it('removeSignalHandlers leaves listeners owned by other code in place', () => {
|
||||
const foreign = () => {};
|
||||
process.on('SIGTERM', foreign);
|
||||
try {
|
||||
const shutdown = track(new Shutdown());
|
||||
shutdown.removeSignalHandlers();
|
||||
|
||||
expect(process.listeners('SIGTERM')).toContain(foreign);
|
||||
expect(listenerCounts()).toEqual({ SIGTERM: baseline.SIGTERM + 1, SIGINT: baseline.SIGINT });
|
||||
} finally {
|
||||
process.off('SIGTERM', foreign);
|
||||
}
|
||||
});
|
||||
|
||||
it('dispose and reset are idempotent', () => {
|
||||
const shutdown = track(new Shutdown());
|
||||
|
||||
shutdown.dispose();
|
||||
shutdown.dispose();
|
||||
Shutdown.reset();
|
||||
Shutdown.reset();
|
||||
|
||||
expect(listenerCounts()).toEqual(baseline);
|
||||
});
|
||||
|
||||
it('repeatedly creating and disposing instances never accumulates listeners', () => {
|
||||
for (let i = 0; i < 25; i++) {
|
||||
new Shutdown().dispose();
|
||||
}
|
||||
|
||||
expect(listenerCounts()).toEqual(baseline);
|
||||
});
|
||||
|
||||
it('Shutdown.reset removes singleton listeners and the next getInstance builds a fresh instance', () => {
|
||||
const first = Shutdown.getInstance();
|
||||
expect(listenerCounts().SIGTERM).toBe(baseline.SIGTERM + 1);
|
||||
|
||||
Shutdown.reset();
|
||||
|
||||
expect(listenerCounts()).toEqual(baseline);
|
||||
const second = Shutdown.getInstance({ autoRegister: false });
|
||||
track(second);
|
||||
expect(second).not.toBe(first);
|
||||
expect(listenerCounts()).toEqual(baseline);
|
||||
});
|
||||
|
||||
it('disposing a non-singleton instance keeps the active singleton and its listeners', () => {
|
||||
const singleton = Shutdown.getInstance();
|
||||
const other = track(new Shutdown());
|
||||
|
||||
other.dispose();
|
||||
|
||||
expect(Shutdown.getInstance()).toBe(singleton);
|
||||
expect(listenerCounts()).toEqual({
|
||||
SIGTERM: baseline.SIGTERM + 1,
|
||||
SIGINT: baseline.SIGINT + 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('disposing the singleton directly clears it so getInstance returns a new one', () => {
|
||||
const singleton = Shutdown.getInstance({ autoRegister: false });
|
||||
|
||||
singleton.dispose();
|
||||
|
||||
const next = Shutdown.getInstance({ autoRegister: false });
|
||||
expect(next).not.toBe(singleton);
|
||||
});
|
||||
|
||||
it('a disposed instance keeps its shutdown callbacks usable without process listeners', async () => {
|
||||
const shutdown = track(new Shutdown({ timeout: 1000 }));
|
||||
const calls: string[] = [];
|
||||
shutdown.onShutdown(() => {
|
||||
calls.push('ran');
|
||||
}, 10, 'probe');
|
||||
|
||||
shutdown.dispose();
|
||||
await shutdown.shutdown();
|
||||
|
||||
expect(calls).toEqual(['ran']);
|
||||
expect(listenerCounts()).toEqual(baseline);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,46 +1,46 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
|
||||
import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { Shutdown } from '../src/shutdown';
|
||||
|
||||
describe('Shutdown Signal Handlers', () => {
|
||||
let shutdown: Shutdown | undefined;
|
||||
let processOnceSpy: ReturnType<typeof spyOn>;
|
||||
let processExitSpy: ReturnType<typeof spyOn>;
|
||||
let shutdown: Shutdown;
|
||||
let processOnceSpy: any;
|
||||
let processExitSpy: any;
|
||||
const originalOn = process.on;
|
||||
const originalExit = process.exit;
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset singleton instance
|
||||
Shutdown.reset();
|
||||
shutdown = undefined;
|
||||
(Shutdown as any).instance = null;
|
||||
|
||||
// Mock process.on to capture signal handlers
|
||||
const listeners: Record<string, Function[]> = {};
|
||||
processOnceSpy = spyOn(process, 'on').mockImplementation(((event: string, handler: Function) => {
|
||||
processOnceSpy = mock((event: string, handler: Function) => {
|
||||
if (!listeners[event]) {
|
||||
listeners[event] = [];
|
||||
}
|
||||
listeners[event].push(handler);
|
||||
return process;
|
||||
}) as any);
|
||||
});
|
||||
process.on = processOnceSpy as any;
|
||||
|
||||
// Mock process.exit
|
||||
processExitSpy = spyOn(process, 'exit').mockImplementation(((_code?: number) => {
|
||||
processExitSpy = mock((_code?: number) => {
|
||||
// Just record the call, don't actually exit
|
||||
return undefined as never;
|
||||
}) as any);
|
||||
});
|
||||
process.exit = processExitSpy as any;
|
||||
|
||||
// Store listeners for manual triggering
|
||||
(global as any).__testListeners = listeners;
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Clean up any registered listeners and singleton before restoring process spies
|
||||
shutdown?.dispose();
|
||||
shutdown = undefined;
|
||||
Shutdown.reset();
|
||||
|
||||
// Restore original methods
|
||||
processOnceSpy?.mockRestore();
|
||||
processExitSpy?.mockRestore();
|
||||
process.on = originalOn;
|
||||
process.exit = originalExit;
|
||||
|
||||
// Clean up
|
||||
(Shutdown as any).instance = null;
|
||||
delete (global as any).__testListeners;
|
||||
});
|
||||
|
||||
|
|
|
|||
|
|
@ -1,18 +1,18 @@
|
|||
import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test';
|
||||
import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test';
|
||||
import { Shutdown } from '../src/shutdown';
|
||||
|
||||
describe('Shutdown', () => {
|
||||
let shutdown: Shutdown;
|
||||
|
||||
beforeEach(() => {
|
||||
// Reset singleton instance and remove any prior signal listeners
|
||||
Shutdown.reset();
|
||||
shutdown = Shutdown.getInstance({ timeout: 1000, autoRegister: false });
|
||||
// Reset singleton instance for each test
|
||||
(Shutdown as any).instance = null;
|
||||
shutdown = Shutdown.getInstance({ timeout: 1000 });
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
// Clean up listeners and singleton
|
||||
Shutdown.reset();
|
||||
// Clean up
|
||||
(Shutdown as any).instance = null;
|
||||
});
|
||||
|
||||
describe('getInstance', () => {
|
||||
|
|
@ -24,8 +24,7 @@ describe('Shutdown', () => {
|
|||
});
|
||||
|
||||
it('should use provided config on first call', () => {
|
||||
Shutdown.reset();
|
||||
const instance = Shutdown.getInstance({ timeout: 5000, autoRegister: false });
|
||||
const instance = Shutdown.getInstance({ timeout: 5000 });
|
||||
expect(instance).toBeDefined();
|
||||
});
|
||||
});
|
||||
|
|
@ -126,45 +125,20 @@ describe('Shutdown', () => {
|
|||
});
|
||||
|
||||
it('should respect timeout', async () => {
|
||||
let releaseHandler!: () => void;
|
||||
const slowHandler = mock(
|
||||
() =>
|
||||
new Promise<void>(resolve => {
|
||||
releaseHandler = resolve;
|
||||
})
|
||||
);
|
||||
const slowHandler = mock(async () => {
|
||||
await new Promise(resolve => setTimeout(resolve, 2000));
|
||||
});
|
||||
|
||||
let scheduledCallback: (() => void) | undefined;
|
||||
let scheduledDelay: number | undefined;
|
||||
const fakeTimer = {} as ReturnType<typeof setTimeout>;
|
||||
const setTimeoutSpy = spyOn(globalThis, 'setTimeout').mockImplementation(((
|
||||
cb: (...args: unknown[]) => void,
|
||||
delay?: number
|
||||
) => {
|
||||
scheduledCallback = () => cb();
|
||||
scheduledDelay = delay;
|
||||
return fakeTimer;
|
||||
}) as unknown as typeof setTimeout);
|
||||
const clearTimeoutSpy = spyOn(globalThis, 'clearTimeout').mockImplementation(() => {});
|
||||
shutdown = Shutdown.getInstance({ timeout: 100 });
|
||||
shutdown.onShutdown(slowHandler, 10, 'Slow Handler');
|
||||
|
||||
try {
|
||||
Shutdown.reset();
|
||||
shutdown = Shutdown.getInstance({ timeout: 100, autoRegister: false });
|
||||
shutdown.onShutdown(slowHandler, 10, 'Slow Handler');
|
||||
const start = Date.now();
|
||||
await expect(shutdown.shutdown()).rejects.toThrow('Shutdown timeout');
|
||||
const duration = Date.now() - start;
|
||||
|
||||
const shutdownPromise = shutdown.shutdown();
|
||||
expect(scheduledDelay).toBe(100);
|
||||
expect(scheduledCallback).toBeDefined();
|
||||
|
||||
scheduledCallback!();
|
||||
|
||||
await expect(shutdownPromise).rejects.toThrow('Shutdown timeout');
|
||||
expect(clearTimeoutSpy).toHaveBeenCalledWith(fakeTimer);
|
||||
} finally {
|
||||
releaseHandler?.();
|
||||
setTimeoutSpy.mockRestore();
|
||||
clearTimeoutSpy.mockRestore();
|
||||
}
|
||||
// Shutdown waits for timeout (100ms) plus some processing time
|
||||
expect(duration).toBeGreaterThan(90);
|
||||
expect(duration).toBeLessThan(1500); // But not the full 2000ms
|
||||
});
|
||||
});
|
||||
|
||||
|
|
@ -187,8 +161,8 @@ describe('Shutdown', () => {
|
|||
await shutdown.shutdown();
|
||||
|
||||
// Reset by creating new instance
|
||||
Shutdown.reset();
|
||||
shutdown = Shutdown.getInstance({ timeout: 1000, autoRegister: false });
|
||||
(Shutdown as any).instance = null;
|
||||
shutdown = Shutdown.getInstance({ timeout: 1000 });
|
||||
|
||||
shutdown.onShutdown(handler, 10, 'Handler');
|
||||
await shutdown.shutdown();
|
||||
|
|
|
|||
|
|
@ -27,7 +27,6 @@
|
|||
"test:integration": "bun test test/integration/",
|
||||
"test:native": "cargo test -p engine --lib --offline",
|
||||
"test:postgres": "bun run scripts/test-postgres.ts",
|
||||
"db:migrate": "bun run scripts/db-migrate.ts",
|
||||
"audit:secrets": "bun run scripts/audit-secrets.ts",
|
||||
"test:e2e": "bun run scripts/test-e2e.ts",
|
||||
"test:e2e:install": "playwright install chromium",
|
||||
|
|
|
|||
|
|
@ -43,13 +43,11 @@ export function findEmbeddedHttpCredentials(content: string): number[] {
|
|||
for (let index = 0; index < lines.length; index++) {
|
||||
const line = lines[index] ?? '';
|
||||
for (const match of line.matchAll(httpCredentialPattern)) {
|
||||
const user = match[1] ?? '';
|
||||
const password = match[2] ?? '';
|
||||
const fullMatch = match[0] ?? '';
|
||||
const host = match[3] ?? '';
|
||||
const normalizedHost = host.replace(/\.$/, '');
|
||||
if (
|
||||
user.includes('${') ||
|
||||
password.includes('${') ||
|
||||
fullMatch.includes('${') ||
|
||||
!normalizedHost ||
|
||||
normalizedHost.startsWith('.') ||
|
||||
isPlaceholderHost(normalizedHost)
|
||||
|
|
|
|||
|
|
@ -247,57 +247,25 @@ async function child(workload: Workload) {
|
|||
};
|
||||
}
|
||||
|
||||
function command(args: string[], cwd: string = root): string {
|
||||
const result = Bun.spawnSync(args, { cwd, stdout: 'pipe', stderr: 'pipe' });
|
||||
function command(args: string[]): string {
|
||||
const result = Bun.spawnSync(args, { cwd: root, stdout: 'pipe', stderr: 'pipe' });
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error(`${args[0]} failed: ${result.stderr.toString()}`);
|
||||
}
|
||||
return result.stdout.toString().trimEnd();
|
||||
}
|
||||
|
||||
function errorCode(error: unknown): string | undefined {
|
||||
if (typeof error === 'object' && error !== null && 'code' in error) {
|
||||
const code = (error as { code?: unknown }).code;
|
||||
return typeof code === 'string' ? code : undefined;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function identity(
|
||||
options: {
|
||||
sourceRoot?: string;
|
||||
readSourceFile?: (path: string) => Uint8Array;
|
||||
} = {}
|
||||
) {
|
||||
const sourceRoot = options.sourceRoot ?? root;
|
||||
const readSourceFile = options.readSourceFile ?? readFileSync;
|
||||
const tracked = new Set(
|
||||
command(['git', 'ls-files', '--cached', '-z'], sourceRoot).split('\0').filter(Boolean)
|
||||
);
|
||||
const paths = command(
|
||||
['git', 'ls-files', '--cached', '--others', '--exclude-standard', '-z'],
|
||||
sourceRoot
|
||||
)
|
||||
export function identity() {
|
||||
const paths = command(['git', 'ls-files', '--cached', '--others', '--exclude-standard', '-z'])
|
||||
.split('\0')
|
||||
.filter(Boolean)
|
||||
.sort();
|
||||
const source = createHash('sha256');
|
||||
for (const path of paths) {
|
||||
const absolute = join(sourceRoot, path);
|
||||
let entry: string;
|
||||
try {
|
||||
entry = sha256(readSourceFile(absolute));
|
||||
} catch (error) {
|
||||
const code = errorCode(error);
|
||||
if (code === 'ENOENT') {
|
||||
entry = 'deleted';
|
||||
} else if ((code === 'EACCES' || code === 'EPERM') && !tracked.has(path)) {
|
||||
entry = 'unreadable';
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
source.update(JSON.stringify([path, entry]));
|
||||
const absolute = join(root, path);
|
||||
source.update(
|
||||
JSON.stringify([path, existsSync(absolute) ? sha256(readFileSync(absolute)) : 'deleted'])
|
||||
);
|
||||
}
|
||||
const addon = join(root, 'apps/stock/engine/dist/engine.node');
|
||||
const nativeSha256 = sha256(readFileSync(addon));
|
||||
|
|
@ -317,12 +285,12 @@ export function identity(
|
|||
};
|
||||
return {
|
||||
source: {
|
||||
commit: command(['git', 'rev-parse', 'HEAD'], sourceRoot),
|
||||
dirty: command(['git', 'status', '--porcelain'], sourceRoot).length > 0,
|
||||
commit: command(['git', 'rev-parse', 'HEAD']),
|
||||
dirty: command(['git', 'status', '--porcelain']).length > 0,
|
||||
contentSha256: source.digest('hex'),
|
||||
files: paths.length,
|
||||
scope:
|
||||
'Tracked and nonignored untracked file paths/content, including dirty changes; unreadable untracked files are hashed by path with an unreadable marker; generated ignored artifacts excluded.',
|
||||
'Tracked and nonignored untracked file paths/content, including dirty changes; generated ignored artifacts excluded.',
|
||||
},
|
||||
native: {
|
||||
path: addon,
|
||||
|
|
|
|||
|
|
@ -1,148 +0,0 @@
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
import {
|
||||
PostgreSQLClient,
|
||||
runPostgresMigrations,
|
||||
type MigrationTrack,
|
||||
type PostgreSQLClientConfig,
|
||||
} from '@stock-bot/postgres';
|
||||
import {
|
||||
assertEnvironmentSafety,
|
||||
initializeStockConfig,
|
||||
type StockAppConfig,
|
||||
} from '@stock-bot/stock-config';
|
||||
|
||||
const VALID_TRACKS = new Set<MigrationTrack>(['master', 'research', 'all']);
|
||||
const TRACK_USAGE = 'Valid tracks: master|research|all';
|
||||
|
||||
export interface DbMigrateArgs {
|
||||
track: MigrationTrack;
|
||||
}
|
||||
|
||||
export interface MigrationTarget {
|
||||
clientConfig: PostgreSQLClientConfig;
|
||||
targetLabel: string;
|
||||
}
|
||||
|
||||
function isValidTrack(value: string): value is MigrationTrack {
|
||||
return VALID_TRACKS.has(value as MigrationTrack);
|
||||
}
|
||||
|
||||
export function parseDbMigrateArgs(argv: readonly string[]): DbMigrateArgs {
|
||||
let track: MigrationTrack = 'all';
|
||||
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const arg = argv[i];
|
||||
if (arg === '--track') {
|
||||
const value = argv[i + 1];
|
||||
if (!value || value.startsWith('-')) {
|
||||
throw new Error(`Missing value for --track. ${TRACK_USAGE}`);
|
||||
}
|
||||
if (!isValidTrack(value)) {
|
||||
throw new Error(`Invalid --track value "${value}". ${TRACK_USAGE}`);
|
||||
}
|
||||
track = value;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (arg.startsWith('--track=')) {
|
||||
const value = arg.slice('--track='.length);
|
||||
if (!isValidTrack(value)) {
|
||||
throw new Error(`Invalid --track value "${value}". ${TRACK_USAGE}`);
|
||||
}
|
||||
track = value;
|
||||
continue;
|
||||
}
|
||||
|
||||
throw new Error(`Unknown argument "${arg}". Usage: db:migrate [--track master|research|all]`);
|
||||
}
|
||||
|
||||
return { track };
|
||||
}
|
||||
|
||||
export function loadMigrationConfig(): StockAppConfig {
|
||||
return initializeStockConfig('dataPipeline', { postgresOnly: true });
|
||||
}
|
||||
|
||||
export function resolveMigrationTarget(
|
||||
config: StockAppConfig,
|
||||
env: Record<string, string | undefined> = process.env
|
||||
): MigrationTarget {
|
||||
const pg = config.database.postgres;
|
||||
if (!pg.enabled) {
|
||||
throw new Error('PostgreSQL is disabled in the active configuration.');
|
||||
}
|
||||
|
||||
// Never allow the shared dev-on-QA override to bypass the PostgreSQL guard in db:migrate,
|
||||
// and disable unrelated MongoDB checks so Postgres migrations only enforce PostgreSQL/environment guards.
|
||||
const { STOCK_BOT_ALLOW_DEV_ON_QA_DB: _ignored, ...safeEnv } = env;
|
||||
assertEnvironmentSafety(
|
||||
{
|
||||
...config,
|
||||
database: {
|
||||
...config.database,
|
||||
mongodb: {
|
||||
...config.database.mongodb,
|
||||
enabled: false,
|
||||
uri: 'mongodb://disabled',
|
||||
readUri: undefined,
|
||||
password: undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
'dataPipeline',
|
||||
safeEnv
|
||||
);
|
||||
|
||||
const clientConfig: PostgreSQLClientConfig = {
|
||||
host: pg.host,
|
||||
port: pg.port,
|
||||
database: pg.database,
|
||||
username: pg.user,
|
||||
password: pg.password,
|
||||
ssl: { enabled: pg.ssl, rejectUnauthorized: true },
|
||||
poolSettings: {
|
||||
min: 0,
|
||||
max: pg.poolSize,
|
||||
idleTimeoutMillis: pg.idleTimeout,
|
||||
},
|
||||
timeouts: { connection: pg.connectionTimeout },
|
||||
};
|
||||
|
||||
return {
|
||||
clientConfig,
|
||||
targetLabel: `${pg.host}:${pg.port}/${pg.database}`,
|
||||
};
|
||||
}
|
||||
|
||||
async function main(argv: readonly string[]): Promise<void> {
|
||||
const { track } = parseDbMigrateArgs(argv);
|
||||
const config = loadMigrationConfig();
|
||||
const { clientConfig, targetLabel } = resolveMigrationTarget(config, process.env);
|
||||
const logger = getLogger('db-migrate');
|
||||
const client = new PostgreSQLClient(clientConfig, logger);
|
||||
|
||||
try {
|
||||
await client.connect();
|
||||
const applied = await runPostgresMigrations(client, { track });
|
||||
console.log(`Target: ${targetLabel} (track: ${track})`);
|
||||
if (applied.length === 0) {
|
||||
console.log('nothing to apply');
|
||||
} else {
|
||||
console.log(`Applied ${applied.length} migration(s):`);
|
||||
for (const filename of applied) {
|
||||
console.log(` - ${filename}`);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
await client.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
if (import.meta.main) {
|
||||
main(process.argv.slice(2)).catch(error => {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
console.error(`db:migrate failed: ${message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
|
@ -1,87 +1,13 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { createHash } from 'node:crypto';
|
||||
import { chmodSync, mkdtempSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { prepareDataset } from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
||||
import {
|
||||
economicHash,
|
||||
identity,
|
||||
parameters,
|
||||
researchFixture,
|
||||
unavailable,
|
||||
verifyRepeats,
|
||||
} from '../benchmark-research';
|
||||
|
||||
function runGit(cwd: string, args: string[]): void {
|
||||
const result = Bun.spawnSync(['git', ...args], {
|
||||
cwd,
|
||||
stdout: 'pipe',
|
||||
stderr: 'pipe',
|
||||
env: {
|
||||
...process.env,
|
||||
GIT_CONFIG_NOSYSTEM: '1',
|
||||
GIT_CONFIG_GLOBAL: '/dev/null',
|
||||
},
|
||||
});
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error(`git ${args.join(' ')} failed: ${result.stderr.toString()}`);
|
||||
}
|
||||
}
|
||||
|
||||
function withTempGitRepo<T>(fn: (repoDir: string, protectForCleanup: (path: string) => void) => T): T {
|
||||
const repoDir = mkdtempSync(join(tmpdir(), 'stock-bot-benchmark-identity-'));
|
||||
const chmodPaths: string[] = [];
|
||||
const protectForCleanup = (path: string) => {
|
||||
chmodPaths.push(path);
|
||||
};
|
||||
try {
|
||||
runGit(repoDir, ['init']);
|
||||
const emptyExcludesPath = join(repoDir, '.git', 'info', 'exclude');
|
||||
writeFileSync(emptyExcludesPath, '');
|
||||
runGit(repoDir, ['config', 'core.excludesFile', emptyExcludesPath]);
|
||||
writeFileSync(join(repoDir, 'tracked.txt'), 'tracked-v1\n');
|
||||
runGit(repoDir, ['add', 'tracked.txt']);
|
||||
runGit(repoDir, [
|
||||
'-c',
|
||||
'user.name=Test User',
|
||||
'-c',
|
||||
'user.email=test@example.com',
|
||||
'commit',
|
||||
'-m',
|
||||
'initial',
|
||||
]);
|
||||
return fn(repoDir, protectForCleanup);
|
||||
} finally {
|
||||
for (const path of chmodPaths) {
|
||||
try {
|
||||
chmodSync(path, 0o600);
|
||||
} catch {
|
||||
// Ignore if file was removed during the test.
|
||||
}
|
||||
}
|
||||
rmSync(repoDir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
function fsError(code: string, path: string): NodeJS.ErrnoException {
|
||||
const error = new Error(`${code}: ${path}`) as NodeJS.ErrnoException;
|
||||
error.code = code;
|
||||
return error;
|
||||
}
|
||||
|
||||
function sha256(data: Uint8Array | string): string {
|
||||
return createHash('sha256').update(data).digest('hex');
|
||||
}
|
||||
|
||||
function expectedSourceSha256(entries: [string, string][]): string {
|
||||
const hash = createHash('sha256');
|
||||
for (const [path, entry] of [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
|
||||
hash.update(JSON.stringify([path, entry]));
|
||||
}
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
describe('existing-path research benchmark', () => {
|
||||
test('fixture is seeded, ordered, hash-verified and detached by real dataset preparation', async () => {
|
||||
for (const assets of [1, 10]) {
|
||||
|
|
@ -216,141 +142,4 @@ describe('existing-path research benchmark', () => {
|
|||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('identity hashes unreadable untracked files deterministically while throwing on tracked or non-permission errors', () => {
|
||||
withTempGitRepo(repoDir => {
|
||||
const untrackedPath = join(repoDir, '.bash_profile');
|
||||
const trackedPath = join(repoDir, 'tracked.txt');
|
||||
writeFileSync(untrackedPath, 'placeholder\n');
|
||||
|
||||
for (const code of ['EACCES', 'EPERM'] as const) {
|
||||
const readSourceFile = (path: string) => {
|
||||
if (path === untrackedPath) {
|
||||
throw fsError(code, path);
|
||||
}
|
||||
return readFileSync(path);
|
||||
};
|
||||
|
||||
const first = identity({ sourceRoot: repoDir, readSourceFile });
|
||||
const second = identity({ sourceRoot: repoDir, readSourceFile });
|
||||
expect(Object.keys(first)).toEqual(['source', 'native', 'runtime', 'host']);
|
||||
expect(first.source.contentSha256).toBe(second.source.contentSha256);
|
||||
expect(first.source.contentSha256).toBe(
|
||||
expectedSourceSha256([
|
||||
['.bash_profile', 'unreadable'],
|
||||
['tracked.txt', sha256(readFileSync(trackedPath))],
|
||||
])
|
||||
);
|
||||
expect(first.source.files).toBe(2);
|
||||
expect(first.source.dirty).toBe(true);
|
||||
expect(first.source.scope).toContain('unreadable');
|
||||
|
||||
// Changing a readable file changes contentSha256.
|
||||
writeFileSync(trackedPath, `tracked-${code}\n`);
|
||||
const afterReadableEdit = identity({ sourceRoot: repoDir, readSourceFile });
|
||||
expect(afterReadableEdit.source.contentSha256).not.toBe(first.source.contentSha256);
|
||||
|
||||
// Tracked files still throw EACCES / EPERM.
|
||||
expect(() =>
|
||||
identity({
|
||||
sourceRoot: repoDir,
|
||||
readSourceFile: path => {
|
||||
if (path === trackedPath) {
|
||||
throw fsError(code, path);
|
||||
}
|
||||
return readFileSync(path);
|
||||
},
|
||||
})
|
||||
).toThrow(code);
|
||||
}
|
||||
|
||||
// Non-permission errors on untracked files still throw.
|
||||
expect(() =>
|
||||
identity({
|
||||
sourceRoot: repoDir,
|
||||
readSourceFile: path => {
|
||||
if (path === untrackedPath) {
|
||||
throw fsError('EIO', path);
|
||||
}
|
||||
return readFileSync(path);
|
||||
},
|
||||
})
|
||||
).toThrow('EIO');
|
||||
|
||||
// Renaming or removing the unreadable untracked file changes contentSha256.
|
||||
const beforeRename = identity({
|
||||
sourceRoot: repoDir,
|
||||
readSourceFile: path => {
|
||||
if (path === untrackedPath) {
|
||||
throw fsError('EACCES', path);
|
||||
}
|
||||
return readFileSync(path);
|
||||
},
|
||||
});
|
||||
const renamedPath = join(repoDir, '.bash_profile_renamed');
|
||||
renameSync(untrackedPath, renamedPath);
|
||||
const afterRename = identity({
|
||||
sourceRoot: repoDir,
|
||||
readSourceFile: path => {
|
||||
if (path === renamedPath) {
|
||||
throw fsError('EACCES', path);
|
||||
}
|
||||
return readFileSync(path);
|
||||
},
|
||||
});
|
||||
expect(afterRename.source.contentSha256).not.toBe(beforeRename.source.contentSha256);
|
||||
|
||||
rmSync(renamedPath);
|
||||
const afterRemove = identity({ sourceRoot: repoDir });
|
||||
expect(afterRemove.source.contentSha256).not.toBe(afterRename.source.contentSha256);
|
||||
expect(afterRemove.source.files).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
test('identity handles real chmod 000 untracked files and rejects chmod 000 tracked files', () => {
|
||||
if (process.getuid?.() === 0) {
|
||||
return;
|
||||
}
|
||||
withTempGitRepo((repoDir, protectForCleanup) => {
|
||||
const trackedPath = join(repoDir, 'tracked.txt');
|
||||
const untrackedPath = join(repoDir, 'unreadable-untracked.txt');
|
||||
writeFileSync(untrackedPath, 'secret\n');
|
||||
chmodSync(untrackedPath, 0o000);
|
||||
protectForCleanup(untrackedPath);
|
||||
|
||||
const first = identity({ sourceRoot: repoDir });
|
||||
const second = identity({ sourceRoot: repoDir });
|
||||
expect(first.source.contentSha256).toBe(second.source.contentSha256);
|
||||
expect(first.source.contentSha256).toBe(
|
||||
expectedSourceSha256([
|
||||
['tracked.txt', sha256(readFileSync(trackedPath))],
|
||||
['unreadable-untracked.txt', 'unreadable'],
|
||||
])
|
||||
);
|
||||
expect(first.source.files).toBe(2);
|
||||
|
||||
writeFileSync(trackedPath, 'tracked-v2\n');
|
||||
const afterEdit = identity({ sourceRoot: repoDir });
|
||||
expect(afterEdit.source.contentSha256).not.toBe(first.source.contentSha256);
|
||||
|
||||
chmodSync(trackedPath, 0o000);
|
||||
protectForCleanup(trackedPath);
|
||||
expect(() => identity({ sourceRoot: repoDir })).toThrow(/EACCES|permission denied/i);
|
||||
});
|
||||
});
|
||||
|
||||
test('identity hashes deleted unstaged tracked files with the deleted marker', () => {
|
||||
withTempGitRepo(repoDir => {
|
||||
const trackedPath = join(repoDir, 'tracked.txt');
|
||||
const beforeDelete = identity({ sourceRoot: repoDir });
|
||||
rmSync(trackedPath);
|
||||
const afterDelete = identity({ sourceRoot: repoDir });
|
||||
expect(afterDelete.source.contentSha256).not.toBe(beforeDelete.source.contentSha256);
|
||||
expect(afterDelete.source.contentSha256).toBe(
|
||||
expectedSourceSha256([['tracked.txt', 'deleted']])
|
||||
);
|
||||
expect(afterDelete.source.files).toBe(1);
|
||||
expect(afterDelete.source.dirty).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,289 +0,0 @@
|
|||
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 { 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-'));
|
||||
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('db-migrate CLI subprocess', () => {
|
||||
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/);
|
||||
});
|
||||
});
|
||||
|
|
@ -1,142 +0,0 @@
|
|||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { Hono } from 'hono';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { ExchangesHandler } from '../../apps/stock/data-pipeline/src/handlers/exchanges/exchanges.handler';
|
||||
import { createPipelineRoutes } from '../../apps/stock/web-api/src/routes/pipeline.routes';
|
||||
import { PipelineService } from '../../apps/stock/web-api/src/services/pipeline.service';
|
||||
|
||||
const repository = fileURLToPath(new URL('../../', import.meta.url));
|
||||
|
||||
function scanSourceFiles(relativeDir: string): string[] {
|
||||
const dir = join(repository, relativeDir);
|
||||
return [...new Bun.Glob('**/*.{ts,tsx}').scanSync({ cwd: dir })].map(file => join(dir, file));
|
||||
}
|
||||
|
||||
describe('legacy sync-ib-exchanges removal', () => {
|
||||
it('legacy MongoDB-writing sync-ib-exchanges operations file does not exist', () => {
|
||||
const legacyFile = join(
|
||||
repository,
|
||||
'apps/stock/data-pipeline/src/handlers/exchanges/operations/sync-ib-exchanges.operations.ts'
|
||||
);
|
||||
expect(existsSync(legacyFile)).toBe(false);
|
||||
});
|
||||
|
||||
it('no source file in data-pipeline, web-api, or web-app references sync-ib-exchanges or syncIBExchanges', () => {
|
||||
const trees = [
|
||||
'apps/stock/data-pipeline/src',
|
||||
'apps/stock/web-api/src',
|
||||
'apps/stock/web-app/src',
|
||||
];
|
||||
const forbiddenSymbols = ['sync-ib-exchanges', 'syncIBExchanges'];
|
||||
const hits: string[] = [];
|
||||
|
||||
for (const tree of trees) {
|
||||
for (const file of scanSourceFiles(tree)) {
|
||||
const content = readFileSync(file, 'utf8');
|
||||
for (const token of forbiddenSymbols) {
|
||||
if (content.includes(token)) {
|
||||
hits.push(`${file}: ${token}`);
|
||||
}
|
||||
}
|
||||
if (tree !== 'apps/stock/data-pipeline/src' && content.includes('/provider-mappings/ib')) {
|
||||
hits.push(`${file}: /provider-mappings/ib`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
expect(hits).toEqual([]);
|
||||
});
|
||||
|
||||
it('POST /api/pipeline/provider-mappings/ib returns 404 without enqueueing jobs while QM mapping route stays active', async () => {
|
||||
const jobs: unknown[] = [];
|
||||
const services = {
|
||||
queueManager: {
|
||||
getQueue() {
|
||||
return {
|
||||
async add(_name: string, data: unknown) {
|
||||
jobs.push(data);
|
||||
return { id: 'fixture' };
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
} as unknown as IServiceContainer;
|
||||
|
||||
const app = new Hono();
|
||||
app.route('/api/pipeline', createPipelineRoutes(services));
|
||||
|
||||
const removed = await app.request('/api/pipeline/provider-mappings/ib', { method: 'POST' });
|
||||
expect(removed.status).toBe(404);
|
||||
expect(jobs).toHaveLength(0);
|
||||
|
||||
const active = await app.request('/api/pipeline/provider-mappings/qm', { method: 'POST' });
|
||||
expect(active.status).toBe(200);
|
||||
expect(jobs).toEqual([
|
||||
{ handler: 'exchanges', operation: 'sync-qm-provider-mappings', payload: {} },
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('exchanges handler after sync-ib-exchanges removal', () => {
|
||||
it('registers exactly the remaining exchange operations and no IB operation', () => {
|
||||
const metadata = ExchangesHandler.extractMetadata();
|
||||
|
||||
expect(metadata?.name).toBe('exchanges');
|
||||
// @Operation + @ScheduledOperation on one method registers the name twice, so compare the set.
|
||||
expect([...new Set(metadata?.operations ?? [])].sort()).toEqual([
|
||||
'clear-postgresql-data',
|
||||
'get-exchange-stats',
|
||||
'get-provider-mapping-stats',
|
||||
'sync-all-exchanges',
|
||||
'sync-qm-exchanges',
|
||||
'sync-qm-provider-mappings',
|
||||
]);
|
||||
});
|
||||
|
||||
it('keeps the other nightly schedules but drops the 03:00 IB exchange schedule', () => {
|
||||
const metadata = ExchangesHandler.extractMetadata();
|
||||
|
||||
const schedules = (metadata?.scheduledJobs ?? [])
|
||||
.map(job => ({ operation: job.operation, cronPattern: job.cronPattern }))
|
||||
.sort((a, b) => a.operation.localeCompare(b.operation));
|
||||
|
||||
expect(schedules).toEqual([
|
||||
{ operation: 'sync-all-exchanges', cronPattern: '0 0 * * 0' },
|
||||
{ operation: 'sync-qm-exchanges', cronPattern: '0 1 * * *' },
|
||||
{ operation: 'sync-qm-provider-mappings', cronPattern: '0 3 * * *' },
|
||||
]);
|
||||
});
|
||||
|
||||
it('rejects a leftover queued sync-ib-exchanges job without touching MongoDB', async () => {
|
||||
const mongoCalls: string[] = [];
|
||||
const mongodb = new Proxy(
|
||||
{},
|
||||
{
|
||||
get(_target, property) {
|
||||
mongoCalls.push(String(property));
|
||||
return () => {
|
||||
throw new Error('MongoDB must not be used');
|
||||
};
|
||||
},
|
||||
}
|
||||
);
|
||||
const handler = new ExchangesHandler({ mongodb } as unknown as IServiceContainer);
|
||||
|
||||
await expect(
|
||||
handler.execute('sync-ib-exchanges', {}, { type: 'queue', metadata: {} } as never)
|
||||
).rejects.toThrow('Unknown operation: sync-ib-exchanges');
|
||||
expect(mongoCalls).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('web-api pipeline service after sync-ib-exchanges removal', () => {
|
||||
it('no longer exposes a method that enqueues sync-ib-exchanges', () => {
|
||||
const service = new PipelineService({} as IServiceContainer);
|
||||
|
||||
expect('syncIBExchanges' in service).toBe(false);
|
||||
expect(typeof service.syncQMProviderMappings).toBe('function');
|
||||
});
|
||||
});
|
||||
|
|
@ -425,95 +425,6 @@ test('embedded HTTP(S) credential audit catches real credentials with line numbe
|
|||
expect(serialized).not.toContain('proxy-user');
|
||||
});
|
||||
|
||||
test('embedded HTTP(S) credential audit reports hardcoded credentials with interpolated hosts and skips interpolated credentials', () => {
|
||||
const buildUrl = (scheme: string, user: string, pass: string, host: string) =>
|
||||
`${scheme}://${user}:${pass}@${host}`;
|
||||
|
||||
const interpHost = buildUrl('http', 'realuser', 'realpass', '${proxyHost}:80');
|
||||
const partialInterpHost = buildUrl('https', 'realuser', 'realpass', 'sub.${domain}/v1');
|
||||
const ipv6InterpHost = buildUrl('http', 'realuser', 'realpass', '[${ipv6Host}]:80');
|
||||
const placeholderSubInterp = buildUrl('http', 'realuser', 'realpass', '${sub}.example.com:80');
|
||||
|
||||
const lines = [
|
||||
'const bothInterpDocHost = `http://${user}:${pass}@host:80`;',
|
||||
'const bothInterpRealHost = `http://${user}:${pass}@proxy.vendor.io:80`;',
|
||||
'const allInterp = `http://${user}:${pass}@${proxyHost}:80`;',
|
||||
'const userOnlyInterp = `http://${user}:realpass@proxy.vendor.io:80`;',
|
||||
'const userOnlyInterpHost = `http://${user}:realpass@${proxyHost}:80`;',
|
||||
'const passOnlyInterp = `http://realuser:${pass}@proxy.vendor.io:80`;',
|
||||
'const passOnlyInterpHost = `http://realuser:${pass}@${proxyHost}:80`;',
|
||||
`const placeholderSub = \`${placeholderSubInterp}\`;`,
|
||||
`const leakedInterpHost = \`${interpHost}\`;`,
|
||||
`const leakedPartialInterpHost = \`${partialInterpHost}\`;`,
|
||||
`const leakedIpv6InterpHost = \`${ipv6InterpHost}\`;`,
|
||||
`const mixedSameLine = [\`http://\${user}:\${pass}@proxy.vendor.io:80\`, \`${interpHost}\`];`,
|
||||
].join('\n');
|
||||
|
||||
expect(findEmbeddedHttpCredentials(lines)).toEqual([9, 10, 11, 12]);
|
||||
|
||||
const files = new Map<string, Buffer>([
|
||||
['apps/stock/proxy.ts', Buffer.from(`const url = \`${interpHost}\`;\n`)],
|
||||
]);
|
||||
const findings = scanTrackedFilesForHttpCredentials(
|
||||
['apps/stock/proxy.ts'],
|
||||
path => files.get(path) ?? null
|
||||
);
|
||||
expect(findings).toEqual([{ path: 'apps/stock/proxy.ts', line: 1 }]);
|
||||
const serialized = JSON.stringify(findings);
|
||||
expect(serialized).not.toContain('realuser');
|
||||
expect(serialized).not.toContain('realpass');
|
||||
|
||||
expect(
|
||||
scanTrackedFilesForHttpCredentials(['scripts/audit-secrets.ts', 'scripts/test/security.test.ts'])
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
test('embedded HTTP(S) credential audit handles interpolated-host edge cases per line', () => {
|
||||
const buildUrl = (scheme: string, user: string, pass: string, host: string) =>
|
||||
`${scheme}://${user}:${pass}@${host}`;
|
||||
|
||||
const interpHost = buildUrl('http', 'edgeuser', 'edgepass', '${proxyHost}:80');
|
||||
const interpHostNoPort = buildUrl('https', 'edgeuser', 'edgepass', '${proxyHost}/v1');
|
||||
const upperScheme = buildUrl('HTTPS', 'edgeuser', 'edgepass', '${proxyHost}');
|
||||
const interpFqdnDot = buildUrl('https', 'edgeuser', 'edgepass', '${region}.vendor.io.:8443');
|
||||
const interpTestTld = buildUrl('http', 'edgeuser', 'edgepass', '${sub}.proxy.test:80');
|
||||
const interpLocalhost = buildUrl('http', 'edgeuser', 'edgepass', 'localhost');
|
||||
|
||||
const lines = [
|
||||
`const reportedFirst = [\`${interpHost}\`, \`http://\${user}:\${pass}@proxy.vendor.io:80\`];`,
|
||||
`const twoLeaks = [\`${interpHost}\`, \`${interpHostNoPort}\`];`,
|
||||
'const partialUser = `http://real${suffix}:realpass@proxy.vendor.io:80`;',
|
||||
'const partialPass = `http://realuser:pre${secret}post@${proxyHost}:80`;',
|
||||
`const upper = \`${upperScheme}\`;`,
|
||||
`const fqdnDot = \`${interpFqdnDot}\`;`,
|
||||
`const testTld = \`${interpTestTld}\`;`,
|
||||
`const local = \`${interpLocalhost}\`;`,
|
||||
].join('\r\n');
|
||||
|
||||
// Line 2 holds two leaks but is reported once; CRLF must not shift line numbers.
|
||||
expect(findEmbeddedHttpCredentials(lines)).toEqual([1, 2, 5, 6]);
|
||||
});
|
||||
|
||||
test('embedded HTTP(S) credential audit self-scan reads both edited sources regardless of cwd', () => {
|
||||
const sources = new Map<string, string>([
|
||||
['scripts/audit-secrets.ts', fileURLToPath(new URL('../audit-secrets.ts', import.meta.url))],
|
||||
['scripts/test/security.test.ts', fileURLToPath(import.meta.url)],
|
||||
]);
|
||||
const read: string[] = [];
|
||||
|
||||
const findings = scanTrackedFilesForHttpCredentials([...sources.keys()], path => {
|
||||
const absolute = sources.get(path);
|
||||
if (!absolute) throw new Error(`unexpected path ${path}`);
|
||||
const content = readFileSync(absolute);
|
||||
expect(content.length).toBeGreaterThan(0);
|
||||
read.push(path);
|
||||
return content;
|
||||
});
|
||||
|
||||
expect(read).toEqual([...sources.keys()]);
|
||||
expect(findings).toEqual([]);
|
||||
});
|
||||
|
||||
function isolatedGitEnv(baseEnv: NodeJS.ProcessEnv = process.env): Record<string, string> {
|
||||
const env: Record<string, string> = {};
|
||||
for (const [key, value] of Object.entries(baseEnv)) {
|
||||
|
|
@ -524,15 +435,12 @@ function isolatedGitEnv(baseEnv: NodeJS.ProcessEnv = process.env): Record<string
|
|||
return env;
|
||||
}
|
||||
|
||||
function runAuditSecretsCliFixture(
|
||||
baseEnv: NodeJS.ProcessEnv = process.env,
|
||||
leakedHost = 'proxy.vendor.io.'
|
||||
) {
|
||||
function runAuditSecretsCliFixture(baseEnv: NodeJS.ProcessEnv = process.env) {
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'audit-secrets-cli-'));
|
||||
const auditScript = fileURLToPath(new URL('../audit-secrets.ts', import.meta.url));
|
||||
const fakeUser = 'cli-audit-user';
|
||||
const fakePass = 'cli-audit-s3cr3t';
|
||||
const leakedUrl = `${'https'}://${fakeUser}:${fakePass}@${leakedHost}`;
|
||||
const leakedUrl = `${'https'}://${fakeUser}:${fakePass}@proxy.vendor.io.`;
|
||||
const env = isolatedGitEnv(baseEnv);
|
||||
|
||||
try {
|
||||
|
|
@ -567,17 +475,6 @@ test('audit-secrets CLI reports path:line to stderr, exits 1, and never echoes c
|
|||
expect(result.stderr).not.toContain(result.fakePass);
|
||||
});
|
||||
|
||||
test('audit-secrets CLI reports hardcoded credentials with an interpolated host without echoing them', () => {
|
||||
const result = runAuditSecretsCliFixture(process.env, '${proxyHost}:80');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('leaked.ts:2');
|
||||
expect(result.stdout).not.toContain(result.fakeUser);
|
||||
expect(result.stdout).not.toContain(result.fakePass);
|
||||
expect(result.stderr).not.toContain(result.fakeUser);
|
||||
expect(result.stderr).not.toContain(result.fakePass);
|
||||
});
|
||||
|
||||
test('audit-secrets CLI fixture ignores inherited Git repository and index env vars', () => {
|
||||
const callerDir = mkdtempSync(join(tmpdir(), 'audit-secrets-caller-'));
|
||||
const cleanEnv = isolatedGitEnv();
|
||||
|
|
|
|||
|
|
@ -1,220 +0,0 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { copyFileSync, mkdtempSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { afterEach, describe, expect, test } from 'bun:test';
|
||||
import { Pool } from 'pg';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient, runPostgresMigrations } from '@stock-bot/postgres';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('fresh-database-schema-test');
|
||||
const url = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const initDir = fileURLToPath(new URL('../../database/postgres/init', import.meta.url));
|
||||
|
||||
const MASTER_FILES = [
|
||||
'01-init-database.sql',
|
||||
'02-master-schema.sql',
|
||||
'03-initial-data.sql',
|
||||
'04-provider-exchange-mapping-schema.sql',
|
||||
'05-add-visible-column.sql',
|
||||
];
|
||||
|
||||
const BOOTSTRAP_FILES = [
|
||||
'06-create-backtest-tables.sql',
|
||||
'07-fix-execution-time-type.sql',
|
||||
'08-create-runs-table.sql',
|
||||
];
|
||||
|
||||
const RESEARCH_FILES = [
|
||||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'11-simulation-execution-ledger.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'13-strategy-recovery.sql',
|
||||
'14-backtest-submission.sql',
|
||||
'15-canonical-paper-intents.sql',
|
||||
'16-strategy-catalog.sql',
|
||||
'17-research-retention.sql',
|
||||
'18-backtest-strategy-versions.sql',
|
||||
'19-canonical-research.sql',
|
||||
'20-research-workspace.sql',
|
||||
'21-run-reproduction.sql',
|
||||
'22-experiments.sql',
|
||||
'23-experiment-retries.sql',
|
||||
'24-chronological-validation.sql',
|
||||
'25-walk-forward.sql',
|
||||
'26-cost-sensitivity.sql',
|
||||
'27-research-evidence-sources.sql',
|
||||
'28-research-agents.sql',
|
||||
'29-isolated-candidates.sql',
|
||||
'30-paper-deployments.sql',
|
||||
'31-research-agent-project-links.sql',
|
||||
'32-candidate-parameter-defaults.sql',
|
||||
'33-candidate-decimal-normalization.sql',
|
||||
];
|
||||
|
||||
const cleanup: (() => Promise<void> | void)[] = [];
|
||||
afterEach(async () => {
|
||||
for (const close of cleanup.splice(0).reverse()) {
|
||||
await close();
|
||||
}
|
||||
});
|
||||
|
||||
async function createIsolatedFixture() {
|
||||
if (!url || !new URL(url).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Dedicated stock_bot_safety database required');
|
||||
}
|
||||
const schema = `stock_bot_safety_${randomUUID().replaceAll('-', '')}`;
|
||||
const admin = new Pool({ connectionString: url });
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
const pool = new Pool({
|
||||
connectionString: url,
|
||||
options: `-c search_path=${schema} -c statement_timeout=5000 -c lock_timeout=5000`,
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
await pool.end();
|
||||
await admin.query(`DROP SCHEMA ${schema} CASCADE`);
|
||||
await admin.end();
|
||||
});
|
||||
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', {
|
||||
get: () => ({
|
||||
connect: () => pool.connect(),
|
||||
}),
|
||||
});
|
||||
|
||||
const tables = async () =>
|
||||
(
|
||||
await pool.query('SELECT tablename FROM pg_tables WHERE schemaname = $1 ORDER BY tablename', [
|
||||
schema,
|
||||
])
|
||||
).rows.map(row => row.tablename as string);
|
||||
|
||||
const recorded = async () =>
|
||||
(await pool.query('SELECT filename FROM migrations ORDER BY filename')).rows.map(
|
||||
row => row.filename as string
|
||||
);
|
||||
|
||||
const hasColumn = async (tableName: string, columnName: string) =>
|
||||
(
|
||||
await pool.query(
|
||||
'SELECT 1 FROM information_schema.columns WHERE table_schema = $1 AND table_name = $2 AND column_name = $3',
|
||||
[schema, tableName, columnName]
|
||||
)
|
||||
).rowCount === 1;
|
||||
|
||||
return { pool, schema, postgres, tables, recorded, hasColumn };
|
||||
}
|
||||
|
||||
describe.skipIf(!url)('fresh PostgreSQL database schema', () => {
|
||||
test('Case A: init SQL 01-33 contain no CREATE DATABASE/\\c and create all master and research tables', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const sqlFiles = readdirSync(initDir)
|
||||
.filter(file => file.endsWith('.sql'))
|
||||
.sort();
|
||||
|
||||
expect(sqlFiles.length).toBeGreaterThanOrEqual(33);
|
||||
|
||||
for (const file of sqlFiles) {
|
||||
const sql = readFileSync(join(initDir, file), 'utf8');
|
||||
expect(sql).not.toMatch(/\bCREATE\s+DATABASE\b/i);
|
||||
expect(sql).not.toMatch(/^\s*\\c(?:\s|$)/m);
|
||||
await f.pool.query(sql);
|
||||
}
|
||||
|
||||
const createdTables = new Set(await f.tables());
|
||||
for (const expectedTable of [
|
||||
// Master tables (02-05)
|
||||
'exchanges',
|
||||
'symbols',
|
||||
'provider_exchange_mappings',
|
||||
'provider_mappings',
|
||||
'sync_status',
|
||||
// Research tables (06-33, including representatives from 12, 16, 20, 22, 28, 30)
|
||||
'backtests',
|
||||
'backtest_results',
|
||||
'runs',
|
||||
'backtest_datasets',
|
||||
'strategies',
|
||||
'research_projects',
|
||||
'research_experiments',
|
||||
'research_agents',
|
||||
'paper_deployments',
|
||||
]) {
|
||||
expect(createdTables.has(expectedTable)).toBe(true);
|
||||
}
|
||||
|
||||
// 05-add-visible-column.sql & 19-canonical-research.sql add columns to existing tables
|
||||
expect(await f.hasColumn('exchanges', 'visible')).toBe(true);
|
||||
expect(await f.hasColumn('backtest_results', 'canonical_result')).toBe(true);
|
||||
});
|
||||
|
||||
test('Case B: master track creates master tables, records exact 5 files, and is idempotent', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
const first = await runPostgresMigrations(f.postgres, { track: 'master' });
|
||||
expect(first).toEqual(MASTER_FILES);
|
||||
expect(await f.recorded()).toEqual(MASTER_FILES);
|
||||
|
||||
const createdTables = new Set(await f.tables());
|
||||
for (const table of [
|
||||
'exchanges',
|
||||
'symbols',
|
||||
'provider_exchange_mappings',
|
||||
'provider_mappings',
|
||||
'sync_status',
|
||||
]) {
|
||||
expect(createdTables.has(table)).toBe(true);
|
||||
}
|
||||
expect(await f.hasColumn('exchanges', 'visible')).toBe(true);
|
||||
|
||||
const second = await runPostgresMigrations(f.postgres, { track: 'master' });
|
||||
expect(second).toEqual([]);
|
||||
expect(await f.recorded()).toEqual(MASTER_FILES);
|
||||
});
|
||||
|
||||
test('Case C: all track with 06-08 pre-applied records master + 09-33 and never records 06-08', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
|
||||
for (const file of BOOTSTRAP_FILES) {
|
||||
await f.pool.query(readFileSync(join(initDir, file), 'utf8'));
|
||||
}
|
||||
|
||||
const expected = [...MASTER_FILES, ...RESEARCH_FILES];
|
||||
const first = await runPostgresMigrations(f.postgres, { track: 'all' });
|
||||
expect(first).toEqual(expected);
|
||||
|
||||
const recorded = await f.recorded();
|
||||
expect(recorded).toEqual(expected);
|
||||
for (const excluded of BOOTSTRAP_FILES) {
|
||||
expect(recorded).not.toContain(excluded);
|
||||
}
|
||||
|
||||
const second = await runPostgresMigrations(f.postgres, { track: 'all' });
|
||||
expect(second).toEqual([]);
|
||||
});
|
||||
|
||||
test('Case D: failing master migration rolls back all DDL and leaves no migrations row', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const tempDir = mkdtempSync(join(tmpdir(), 'stock-bot-migrate-fail-'));
|
||||
cleanup.push(() => {
|
||||
rmSync(tempDir, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
copyFileSync(join(initDir, '01-init-database.sql'), join(tempDir, '01-init-database.sql'));
|
||||
copyFileSync(join(initDir, '02-master-schema.sql'), join(tempDir, '02-master-schema.sql'));
|
||||
writeFileSync(join(tempDir, '03-initial-data.sql'), 'SELECT 1 / 0;\n', 'utf8');
|
||||
|
||||
await expect(
|
||||
runPostgresMigrations(f.postgres, { track: 'master', migrationsDir: tempDir })
|
||||
).rejects.toThrow(/division by zero/i);
|
||||
|
||||
expect(await f.tables()).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
|
@ -9,13 +9,7 @@
|
|||
// Bun.timeout = 30000;
|
||||
|
||||
// Store original console methods to allow restoration
|
||||
const originalConsoleMethods = {
|
||||
log: console.log.bind(console),
|
||||
debug: console.debug.bind(console),
|
||||
info: console.info.bind(console),
|
||||
warn: console.warn.bind(console),
|
||||
error: console.error.bind(console),
|
||||
};
|
||||
const originalConsole = global.console;
|
||||
|
||||
// Mock console methods to reduce noise during tests
|
||||
// These can be restored with testHelpers.restoreConsole()
|
||||
|
|
@ -104,11 +98,7 @@ global.testHelpers = {
|
|||
* Restore console methods
|
||||
*/
|
||||
restoreConsole: () => {
|
||||
console.log = originalConsoleMethods.log;
|
||||
console.debug = originalConsoleMethods.debug;
|
||||
console.info = originalConsoleMethods.info;
|
||||
console.warn = originalConsoleMethods.warn;
|
||||
console.error = originalConsoleMethods.error;
|
||||
global.console = originalConsole;
|
||||
}
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -1,242 +0,0 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import {
|
||||
chmodSync,
|
||||
mkdirSync,
|
||||
mkdtempSync,
|
||||
readFileSync,
|
||||
rmSync,
|
||||
symlinkSync,
|
||||
writeFileSync,
|
||||
} from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { identity } from '../../scripts/benchmark-research';
|
||||
|
||||
// Guards T-23: benchmark provenance must tolerate unreadable *untracked* files (sandbox
|
||||
// placeholder dotfiles) without masking read failures on tracked sources, and must keep
|
||||
// readable/deleted digests identical to the pre-fix algorithm.
|
||||
|
||||
const runningAsRoot = process.getuid?.() === 0;
|
||||
|
||||
function git(cwd: string, args: string[]): string {
|
||||
const result = Bun.spawnSync(
|
||||
['git', '-c', 'user.name=QA', '-c', 'user.email=qa@example.com', ...args],
|
||||
{
|
||||
cwd,
|
||||
stdout: 'pipe',
|
||||
stderr: 'pipe',
|
||||
env: { ...process.env, GIT_CONFIG_NOSYSTEM: '1', GIT_CONFIG_GLOBAL: '/dev/null' },
|
||||
}
|
||||
);
|
||||
if (result.exitCode !== 0) {
|
||||
throw new Error(`git ${args.join(' ')} failed: ${result.stderr.toString()}`);
|
||||
}
|
||||
return result.stdout.toString().trim();
|
||||
}
|
||||
|
||||
function sha256(data: Uint8Array | string): string {
|
||||
return createHash('sha256').update(data).digest('hex');
|
||||
}
|
||||
|
||||
// Mirrors the digest identity() builds: sorted paths, each hashed as JSON [path, entry].
|
||||
function expectedDigest(entries: Array<[string, string]>): string {
|
||||
const hash = createHash('sha256');
|
||||
for (const pair of [...entries].sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) {
|
||||
hash.update(JSON.stringify(pair));
|
||||
}
|
||||
return hash.digest('hex');
|
||||
}
|
||||
|
||||
function withRepo(
|
||||
files: Record<string, string>,
|
||||
fn: (repo: string, restoreLater: (path: string, mode: number) => void) => void
|
||||
): void {
|
||||
const repo = mkdtempSync(join(tmpdir(), 'stock-bot-identity-edge-'));
|
||||
const restores: Array<[string, number]> = [];
|
||||
try {
|
||||
git(repo, ['init', '-q']);
|
||||
const excludes = join(repo, '.git', 'info', 'exclude');
|
||||
writeFileSync(excludes, '');
|
||||
git(repo, ['config', 'core.excludesFile', excludes]);
|
||||
for (const [path, content] of Object.entries(files)) {
|
||||
mkdirSync(join(repo, path, '..'), { recursive: true });
|
||||
writeFileSync(join(repo, path), content);
|
||||
}
|
||||
git(repo, ['add', '-A']);
|
||||
git(repo, ['commit', '-qm', 'fixture']);
|
||||
fn(repo, (path, mode) => restores.push([path, mode]));
|
||||
} finally {
|
||||
for (const [path, mode] of restores.reverse()) {
|
||||
try {
|
||||
chmodSync(path, mode);
|
||||
} catch {
|
||||
// Already removed by the test.
|
||||
}
|
||||
}
|
||||
rmSync(repo, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
describe('benchmark identity() edge cases (T-23)', () => {
|
||||
test('readable-only repo digest is byte-for-byte the pre-fix algorithm, including awkward names', () => {
|
||||
const files = { 'name with space.txt': 'a\n', 'ünïcode.txt': 'b\n', 'dir/nested.txt': 'c\n' };
|
||||
withRepo(files, repo => {
|
||||
writeFileSync(join(repo, 'untracked.txt'), 'u\n');
|
||||
|
||||
const result = identity({ sourceRoot: repo });
|
||||
|
||||
expect(result.source.contentSha256).toBe(
|
||||
expectedDigest([
|
||||
...Object.entries(files).map(([p, c]): [string, string] => [p, sha256(c)]),
|
||||
['untracked.txt', sha256('u\n')],
|
||||
])
|
||||
);
|
||||
expect(result.source.files).toBe(4);
|
||||
});
|
||||
});
|
||||
|
||||
test('sourceRoot drives every git query, so commit and dirty describe the temp repo', () => {
|
||||
withRepo({ 'a.txt': 'a\n' }, repo => {
|
||||
const head = git(repo, ['rev-parse', 'HEAD']);
|
||||
|
||||
const clean = identity({ sourceRoot: repo });
|
||||
writeFileSync(join(repo, 'a.txt'), 'changed\n');
|
||||
const dirty = identity({ sourceRoot: repo });
|
||||
|
||||
expect(clean.source.commit).toBe(head);
|
||||
expect(clean.source.dirty).toBe(false);
|
||||
expect(dirty.source.commit).toBe(head);
|
||||
expect(dirty.source.dirty).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
test('dangling untracked symlink still hashes as deleted, as before the fix', () => {
|
||||
withRepo({ 'a.txt': 'a\n' }, repo => {
|
||||
symlinkSync('missing-target', join(repo, 'dangling'));
|
||||
|
||||
const result = identity({ sourceRoot: repo });
|
||||
|
||||
expect(result.source.contentSha256).toBe(
|
||||
expectedDigest([
|
||||
['a.txt', sha256('a\n')],
|
||||
['dangling', 'deleted'],
|
||||
])
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test.skipIf(runningAsRoot)(
|
||||
'untracked symlink to an unreadable target hashes as unreadable instead of throwing',
|
||||
() => {
|
||||
withRepo({ 'a.txt': 'a\n' }, (repo, restoreLater) => {
|
||||
const secret = join(repo, 'secret');
|
||||
writeFileSync(secret, 's\n');
|
||||
chmodSync(secret, 0o000);
|
||||
restoreLater(secret, 0o600);
|
||||
symlinkSync('secret', join(repo, 'link'));
|
||||
|
||||
const first = identity({ sourceRoot: repo });
|
||||
const second = identity({ sourceRoot: repo });
|
||||
|
||||
const expected = expectedDigest([
|
||||
['a.txt', sha256('a\n')],
|
||||
['link', 'unreadable'],
|
||||
['secret', 'unreadable'],
|
||||
]);
|
||||
expect(first.source.contentSha256).toBe(expected);
|
||||
expect(second.source.contentSha256).toBe(expected);
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
test.skipIf(runningAsRoot)(
|
||||
'unreadable untracked directory does not break identity (git cannot list its contents)',
|
||||
() => {
|
||||
withRepo({ 'a.txt': 'a\n' }, (repo, restoreLater) => {
|
||||
const dir = join(repo, 'locked');
|
||||
mkdirSync(dir);
|
||||
writeFileSync(join(dir, 'inside.txt'), 'x\n');
|
||||
chmodSync(dir, 0o000);
|
||||
restoreLater(dir, 0o755);
|
||||
|
||||
const result = identity({ sourceRoot: repo });
|
||||
|
||||
expect(result.source.contentSha256).toBe(expectedDigest([['a.txt', sha256('a\n')]]));
|
||||
expect(result.source.files).toBe(1);
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
test.skipIf(runningAsRoot)(
|
||||
'tracked file under a non-searchable directory throws EACCES instead of hashing as deleted',
|
||||
() => {
|
||||
withRepo({ 'a.txt': 'a\n', 'src/core.ts': 'export {};\n' }, (repo, restoreLater) => {
|
||||
const dir = join(repo, 'src');
|
||||
chmodSync(dir, 0o600);
|
||||
restoreLater(dir, 0o755);
|
||||
|
||||
expect(() => identity({ sourceRoot: repo })).toThrow(/EACCES.*src\/core\.ts/);
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
test.skipIf(runningAsRoot)(
|
||||
'file removed from the index with git rm --cached is treated as untracked and tolerated when unreadable',
|
||||
() => {
|
||||
withRepo({ 'a.txt': 'a\n', 'was-tracked.txt': 'w\n' }, (repo, restoreLater) => {
|
||||
const path = join(repo, 'was-tracked.txt');
|
||||
git(repo, ['rm', '-q', '--cached', 'was-tracked.txt']);
|
||||
chmodSync(path, 0o000);
|
||||
restoreLater(path, 0o600);
|
||||
|
||||
const result = identity({ sourceRoot: repo });
|
||||
|
||||
expect(result.source.contentSha256).toBe(
|
||||
expectedDigest([
|
||||
['a.txt', sha256('a\n')],
|
||||
['was-tracked.txt', 'unreadable'],
|
||||
])
|
||||
);
|
||||
});
|
||||
}
|
||||
);
|
||||
|
||||
test('staged-but-uncommitted file counts as tracked, so a permission error on it still throws', () => {
|
||||
withRepo({ 'a.txt': 'a\n' }, repo => {
|
||||
const staged = join(repo, 'staged.txt');
|
||||
writeFileSync(staged, 's\n');
|
||||
git(repo, ['add', 'staged.txt']);
|
||||
|
||||
const readSourceFile = (path: string): Uint8Array => {
|
||||
if (path === staged) {
|
||||
throw Object.assign(new Error(`EACCES: ${path}`), { code: 'EACCES' });
|
||||
}
|
||||
return readFileSync(path);
|
||||
};
|
||||
|
||||
expect(() => identity({ sourceRoot: repo, readSourceFile })).toThrow('EACCES');
|
||||
});
|
||||
});
|
||||
|
||||
test('errors without a string code are rethrown, never mapped to a marker', () => {
|
||||
withRepo({ 'a.txt': 'a\n' }, repo => {
|
||||
writeFileSync(join(repo, 'untracked.txt'), 'u\n');
|
||||
const target = join(repo, 'untracked.txt');
|
||||
|
||||
for (const thrown of [
|
||||
new Error('plain failure'),
|
||||
Object.assign(new Error('numeric'), { code: 13 }),
|
||||
]) {
|
||||
const readSourceFile = (path: string): Uint8Array => {
|
||||
if (path === target) {
|
||||
throw thrown;
|
||||
}
|
||||
return readFileSync(path);
|
||||
};
|
||||
|
||||
expect(() => identity({ sourceRoot: repo, readSourceFile })).toThrow(thrown.message);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
@ -1,208 +0,0 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { MongoClient } from 'mongodb';
|
||||
import { ServiceContainerBuilder } from '@stock-bot/di';
|
||||
import { setLoggerConfig } from '@stock-bot/logger';
|
||||
import { assertEnvironmentSafety, stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config';
|
||||
|
||||
// T-9 QA: multi-host (seed list) MongoDB URIs and the dev QA-Mongo guard.
|
||||
// The installed MongoDB driver is used only as a parsing oracle (new MongoClient
|
||||
// parses the URI without connecting). Nothing here opens a socket.
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
|
||||
const DEV_MONGO_URI = 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin';
|
||||
const WRITE_ERROR = /cannot open a writable MongoDB connection to QA MongoDB/;
|
||||
const PIPELINE_ERROR = /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/;
|
||||
|
||||
function makeConfig(o: {
|
||||
mongoUri?: string;
|
||||
mongoReadUri?: string | null;
|
||||
mongoReadOnly?: boolean;
|
||||
mongoDatabase?: string;
|
||||
} = {}): StockAppConfig {
|
||||
const mongodb: Record<string, unknown> = {
|
||||
enabled: true,
|
||||
uri: o.mongoUri ?? DEV_MONGO_URI,
|
||||
readOnly: o.mongoReadOnly ?? false,
|
||||
database: o.mongoDatabase ?? 'stock_dev',
|
||||
};
|
||||
if (o.mongoReadUri !== null && o.mongoReadUri !== undefined) {
|
||||
mongodb.readUri = o.mongoReadUri;
|
||||
}
|
||||
return stockAppSchema.parse({
|
||||
name: 'stock-bot',
|
||||
version: '1.0.0',
|
||||
environment: 'development',
|
||||
service: { name: 'stock-bot', port: 2002, host: '127.0.0.1' },
|
||||
log: { level: 'info', format: 'json' },
|
||||
database: {
|
||||
postgres: {
|
||||
enabled: true,
|
||||
host: 'localhost',
|
||||
port: 5433,
|
||||
database: 'trading_bot_dev',
|
||||
user: 'dev_user',
|
||||
password: 'dev_pass',
|
||||
ssl: false,
|
||||
},
|
||||
mongodb,
|
||||
questdb: { enabled: false, host: 'localhost', ilpPort: 9010, httpPort: 9100, pgPort: 8813 },
|
||||
dragonfly: { enabled: true, host: 'localhost', port: 6380 },
|
||||
},
|
||||
providers: {
|
||||
yahoo: { name: 'yahoo', enabled: false, priority: 1, timeout: 30000, baseUrl: 'https://query1.finance.yahoo.com' },
|
||||
qm: { name: 'qm', enabled: false, priority: 2, username: '', password: '', baseUrl: 'https://app.quotemedia.com/quotetools', webmasterId: '' },
|
||||
ib: { name: 'ib', enabled: false, priority: 3, gateway: { host: 'localhost', port: 5000, clientId: 1 }, marketDataType: 'delayed' },
|
||||
eod: { name: 'eod', enabled: false, priority: 4, apiKey: '', baseUrl: 'https://eodhistoricaldata.com/api', tier: 'free' },
|
||||
},
|
||||
features: {},
|
||||
});
|
||||
}
|
||||
|
||||
/** Independent oracle: does the real driver resolve any seed to a plain loopback :27017 address? */
|
||||
function driverSeesQaSeed(uri: string): boolean {
|
||||
const client = new MongoClient(uri);
|
||||
return client.options.hosts.some(h => {
|
||||
const host = (h.host ?? '').toLowerCase();
|
||||
const loopback = host === 'localhost' || host === '::1' || host === '0.0.0.0' || /^127\.\d+\.\d+\.\d+$/.test(host);
|
||||
return loopback && h.port === 27017;
|
||||
});
|
||||
}
|
||||
|
||||
describe('T-9 guard verdict matches the driver for seed lists that pass schema validation', () => {
|
||||
const qaSeedLists = [
|
||||
'mongodb://u:p@localhost:27017,localhost:27018/stock',
|
||||
'mongodb://u:p@localhost:27018,localhost:27017/stock_dev',
|
||||
'mongodb://u:p@db1.dev.internal:27018,db2.dev.internal:27018,127.0.0.1:27017/stock_dev',
|
||||
'mongodb://u:p@localhost:27018,localhost:27019,localhost/stock_dev?replicaSet=rs0',
|
||||
'mongodb://u:p@localhost:27018,0.0.0.0:27017/stock_dev',
|
||||
'mongodb://u:p@localhost:27018,localhost:027017/stock_dev',
|
||||
'mongodb://u:p,w@localhost:27018,localhost:27017/stock',
|
||||
'mongodb://localhost:27018,localhost:27017',
|
||||
];
|
||||
const safeSeedLists = [
|
||||
'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin',
|
||||
// localhost:27017 only inside the query string is not a seed host.
|
||||
'mongodb://u:p@localhost:27018,localhost:27019/stock_dev?appName=localhost:27017',
|
||||
'mongodb://u:p@10.0.0.51:27017,10.0.0.52:27017/stock',
|
||||
];
|
||||
|
||||
for (const uri of qaSeedLists) {
|
||||
test(`blocks writable dataIngestion and non-readOnly dataPipeline on ${uri}`, () => {
|
||||
expect(driverSeesQaSeed(uri)).toBe(true);
|
||||
|
||||
const ingestion = makeConfig({ mongoUri: uri, mongoDatabase: 'stock' });
|
||||
expect(() => assertEnvironmentSafety(ingestion, 'dataIngestion', {})).toThrow(WRITE_ERROR);
|
||||
|
||||
const pipeline = makeConfig({ mongoReadUri: uri, mongoReadOnly: false });
|
||||
expect(() => assertEnvironmentSafety(pipeline, 'dataPipeline', {})).toThrow(PIPELINE_ERROR);
|
||||
});
|
||||
}
|
||||
|
||||
for (const uri of safeSeedLists) {
|
||||
test(`allows dev dataIngestion and dataPipeline on ${uri}`, () => {
|
||||
expect(driverSeesQaSeed(uri)).toBe(false);
|
||||
|
||||
const ingestion = makeConfig({ mongoUri: uri });
|
||||
expect(() => assertEnvironmentSafety(ingestion, 'dataIngestion', {})).not.toThrow();
|
||||
|
||||
const pipeline = makeConfig({ mongoReadUri: uri, mongoReadOnly: false });
|
||||
expect(() => assertEnvironmentSafety(pipeline, 'dataPipeline', {})).not.toThrow();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe('T-9 guard: every non-pipeline dev service is covered for seed lists', () => {
|
||||
const qaSeedList = 'mongodb://u:p@localhost:27018,localhost:27017/stock';
|
||||
|
||||
test('webApi, orchestrator and an unnamed service are blocked from writing', () => {
|
||||
const cfg = makeConfig({ mongoUri: qaSeedList, mongoDatabase: 'stock' });
|
||||
expect(() => assertEnvironmentSafety(cfg, 'webApi', {})).toThrow(/"webApi"/);
|
||||
expect(() => assertEnvironmentSafety(cfg, 'orchestrator', {})).toThrow(/"orchestrator"/);
|
||||
expect(() => assertEnvironmentSafety(cfg, undefined, {})).toThrow(/"app"/);
|
||||
});
|
||||
|
||||
test('pipeline without readUri falls back to a seed-list uri and blocks trading_admin', () => {
|
||||
const cfg = makeConfig({
|
||||
mongoUri: 'mongodb://trading_admin:pw@localhost:27018,localhost:27017/stock',
|
||||
mongoReadUri: null,
|
||||
mongoReadOnly: true,
|
||||
mongoDatabase: 'stock',
|
||||
});
|
||||
expect(cfg.database.mongodb.readUri).toBeUndefined();
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR);
|
||||
});
|
||||
|
||||
test('pipeline without readUri allows the read user on a seed-list uri in readOnly mode', () => {
|
||||
const cfg = makeConfig({
|
||||
mongoUri: 'mongodb://studio_stock_bot_read:pw@localhost:27018,localhost:27017/stock',
|
||||
mongoReadUri: null,
|
||||
mongoReadOnly: true,
|
||||
mongoDatabase: 'stock',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('T-9 guard: seed lists the driver accepts but the schema rejects still fail closed', () => {
|
||||
// The driver tolerates empty seed entries; the guard must not treat them as a
|
||||
// reason to drop the QA seed.
|
||||
const driverAcceptedSchemaRejected = [
|
||||
'mongodb://u:p@localhost:27018,,localhost:27017/stock',
|
||||
'mongodb://u:p@localhost:27018,localhost:27017,/stock',
|
||||
];
|
||||
|
||||
for (const uri of driverAcceptedSchemaRejected) {
|
||||
test(`schema rejects but guard still blocks ${uri}`, () => {
|
||||
expect(driverSeesQaSeed(uri)).toBe(true);
|
||||
expect(() => makeConfig({ mongoUri: uri })).toThrow(/Invalid MongoDB connection URI/);
|
||||
|
||||
const cfg = makeConfig();
|
||||
cfg.database.mongodb.uri = uri;
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow(WRITE_ERROR);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe('T-9 container: read-only database selection agrees with the driver', () => {
|
||||
const cases: Array<{ readUri: string; expected: string }> = [
|
||||
{ readUri: 'mongodb://r:pw@localhost:27017,localhost:27018/stock?authSource=stock', expected: 'stock' },
|
||||
{ readUri: 'mongodb://r:pw@h1.internal:27017,h2.internal/stock%5Fqa?authSource=admin', expected: 'stock_qa' },
|
||||
{ readUri: 'mongodb://r:pw@h1.internal,h2.internal/stock#frag', expected: 'stock' },
|
||||
// No database in the URI: the container keeps the configured database.
|
||||
{ readUri: 'mongodb://r:pw@h1.internal:27017,h2.internal:27018/?replicaSet=rs0', expected: 'stock_dev' },
|
||||
{ readUri: 'mongodb://r:pw@h1.internal,h2.internal', expected: 'stock_dev' },
|
||||
];
|
||||
|
||||
for (const { readUri, expected } of cases) {
|
||||
test(`selects "${expected}" for ${readUri}`, async () => {
|
||||
const driverDb = new MongoClient(readUri).options.dbName;
|
||||
// The driver defaults to "test" when the URI has no database; the container uses config.
|
||||
expect(driverDb === 'test' ? 'stock_dev' : driverDb).toBe(expected);
|
||||
|
||||
const cfg = makeConfig({ mongoReadUri: readUri, mongoReadOnly: true });
|
||||
const { container, shutdown } = await new ServiceContainerBuilder()
|
||||
.withConfig(cfg)
|
||||
.withOptions({
|
||||
enableMongoDB: true,
|
||||
mongoReadOnly: true,
|
||||
enablePostgres: false,
|
||||
enableQuestDB: false,
|
||||
enableCache: false,
|
||||
enableQueue: false,
|
||||
enableBrowser: false,
|
||||
enableProxy: false,
|
||||
skipInitialization: true,
|
||||
})
|
||||
.buildOwned();
|
||||
try {
|
||||
const mongo = container.resolve('mongoClient');
|
||||
expect(mongo).not.toBeNull();
|
||||
expect(mongo!.isReadOnly()).toBe(true);
|
||||
expect(mongo!.getDefaultDatabase()).toBe(expected);
|
||||
} finally {
|
||||
await shutdown();
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
|
@ -24,14 +24,8 @@ function makeConfig(overrides: {
|
|||
mongoReadOnly?: boolean;
|
||||
mongoDatabase?: string;
|
||||
dragonflyPassword?: string;
|
||||
bypassSchemaValidation?: boolean;
|
||||
} = {}): StockAppConfig {
|
||||
const defaultMongoUri =
|
||||
'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin';
|
||||
const defaultMongoReadUri =
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock';
|
||||
|
||||
const parsed = stockAppSchema.parse({
|
||||
return stockAppSchema.parse({
|
||||
name: 'stock-bot',
|
||||
version: '1.0.0',
|
||||
environment: overrides.environment ?? 'development',
|
||||
|
|
@ -56,12 +50,12 @@ function makeConfig(overrides: {
|
|||
},
|
||||
mongodb: {
|
||||
enabled: true,
|
||||
uri: overrides.bypassSchemaValidation
|
||||
? defaultMongoUri
|
||||
: (overrides.mongoUri ?? defaultMongoUri),
|
||||
readUri: overrides.bypassSchemaValidation
|
||||
? defaultMongoReadUri
|
||||
: (overrides.mongoReadUri ?? defaultMongoReadUri),
|
||||
uri:
|
||||
overrides.mongoUri ??
|
||||
'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin',
|
||||
readUri:
|
||||
overrides.mongoReadUri ??
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock',
|
||||
readOnly: overrides.mongoReadOnly ?? false,
|
||||
database: overrides.mongoDatabase ?? 'stock_dev',
|
||||
},
|
||||
|
|
@ -87,17 +81,6 @@ function makeConfig(overrides: {
|
|||
},
|
||||
features: {},
|
||||
});
|
||||
|
||||
if (overrides.bypassSchemaValidation) {
|
||||
if (overrides.mongoUri !== undefined) {
|
||||
parsed.database.mongodb.uri = overrides.mongoUri;
|
||||
}
|
||||
if (overrides.mongoReadUri !== undefined) {
|
||||
parsed.database.mongodb.readUri = overrides.mongoReadUri;
|
||||
}
|
||||
}
|
||||
|
||||
return parsed;
|
||||
}
|
||||
|
||||
describe('Environment safety & multi-env isolation', () => {
|
||||
|
|
@ -264,261 +247,6 @@ describe('Environment safety & multi-env isolation', () => {
|
|||
);
|
||||
});
|
||||
|
||||
test('blocks multi-host MongoDB seed lists targeting QA loopback :27017 for dataIngestion and dataPipeline', () => {
|
||||
const qaFirstIngestion = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: 'mongodb://u:p@localhost:27017,localhost:27018/stock',
|
||||
mongoDatabase: 'stock',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(qaFirstIngestion, 'dataIngestion', {})).toThrow(
|
||||
/cannot open a writable MongoDB connection to QA MongoDB/
|
||||
);
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(qaFirstIngestion, 'dataIngestion', {
|
||||
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
|
||||
})
|
||||
).not.toThrow();
|
||||
|
||||
const qaSecondIngestion = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: 'mongodb://u:p@localhost:27018,localhost:27017/stock_dev',
|
||||
mongoDatabase: 'stock_dev',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(qaSecondIngestion, 'dataIngestion', {})).toThrow(
|
||||
/cannot open a writable MongoDB connection to QA MongoDB/
|
||||
);
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(qaSecondIngestion, 'dataIngestion', {
|
||||
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
|
||||
})
|
||||
).not.toThrow();
|
||||
|
||||
const qaPipelineNonReadOnly = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27018,localhost:27017/stock_dev',
|
||||
mongoReadOnly: false,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(qaPipelineNonReadOnly, 'dataPipeline', {})).toThrow(
|
||||
/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/
|
||||
);
|
||||
|
||||
const qaPipelineFallbackUri = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: 'mongodb://studio_stock_bot_read:secret@localhost:27018,localhost:27017/stock',
|
||||
mongoReadOnly: false,
|
||||
});
|
||||
qaPipelineFallbackUri.database.mongodb.readUri = undefined;
|
||||
expect(() => assertEnvironmentSafety(qaPipelineFallbackUri, 'dataPipeline', {})).toThrow(
|
||||
/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/
|
||||
);
|
||||
|
||||
const qaPipelineAdmin = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://trading_admin:pass@localhost:27017,localhost:27018/stock',
|
||||
mongoReadOnly: true,
|
||||
});
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(qaPipelineAdmin, 'dataPipeline', {
|
||||
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
|
||||
})
|
||||
).toThrow(/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/);
|
||||
|
||||
const qaPipelineEncodedAdmin = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://trading%5Fadmin:pass@localhost:27018,localhost:27017/stock',
|
||||
mongoReadOnly: true,
|
||||
});
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(qaPipelineEncodedAdmin, 'dataPipeline', {
|
||||
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
|
||||
})
|
||||
).toThrow(/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/);
|
||||
|
||||
const qaPipelineReadOnlyAllowed = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock',
|
||||
mongoReadOnly: true,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(qaPipelineReadOnlyAllowed, 'dataPipeline', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test('blocks omitted port, loopback variants, and mongodb+srv loopback URIs', () => {
|
||||
const qaLoopbackUris = [
|
||||
'mongodb://u:p@localhost:27018,localhost/stock_dev',
|
||||
'mongodb://u:p@localhost:27018,127.0.0.1/stock_dev',
|
||||
'mongodb://u:p@localhost:27018,[::1]:27017/stock_dev',
|
||||
'mongodb://u:p@localhost:27018,[::1]/stock_dev',
|
||||
'mongodb://u:p@[0:0:0:0:0:0:0:0001]:27017/stock',
|
||||
'mongodb://u:p@[::ffff:7f00:1]:27017/stock',
|
||||
'mongodb://u:p@[::ffff:7f00:0001]/stock',
|
||||
'mongodb://u:p@[::ffff:7f01:0203]:27017/stock',
|
||||
'mongodb://u:p@[0:0:0:0:0:ffff:7f00:1]:27017/stock',
|
||||
'mongodb://u:p@[::ffff:127.0.0.2]:27017/stock',
|
||||
'mongodb://u:p@localhost:27018,LOCALHOST.:27017/stock_dev',
|
||||
'mongodb://u:p@127.0.0.2:27017/stock_dev',
|
||||
'mongodb+srv://u:p@localhost/stock',
|
||||
];
|
||||
|
||||
for (const mongoUri of qaLoopbackUris) {
|
||||
const cfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri,
|
||||
mongoDatabase: 'stock_dev',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow(
|
||||
/cannot open a writable MongoDB connection to QA MongoDB/
|
||||
);
|
||||
}
|
||||
|
||||
// Non-loopback IPv4-mapped IPv6 addresses must not false-positive as QA loopback
|
||||
const nonLoopbackMappedCfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: 'mongodb://u:p@[::ffff:0a00:1]:27017/stock_dev',
|
||||
mongoDatabase: 'stock_dev',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(nonLoopbackMappedCfg, 'dataIngestion', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test('handles multi-host MongoDB URI parsing edge cases without failing open', () => {
|
||||
const unencodedAtPipeline = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock',
|
||||
mongoReadOnly: true,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(unencodedAtPipeline, 'dataPipeline', {})).toThrow(
|
||||
/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/
|
||||
);
|
||||
|
||||
const edgeCaseUris = [
|
||||
{ uri: 'mongodb://trading_admin:p@ss@localhost:27018,localhost:27017/stock', malformed: false },
|
||||
{ uri: 'mongodb://localhost:27017,localhost:27018/stock', malformed: false },
|
||||
{ uri: 'mongodb://u:p@localhost:/stock', malformed: false },
|
||||
{ uri: 'mongodb://u:p@[::1]:/stock', malformed: false },
|
||||
{ uri: 'mongodb://u:p@bad:port,localhost:27017/stock', malformed: true },
|
||||
];
|
||||
|
||||
for (const { uri: mongoUri, malformed } of edgeCaseUris) {
|
||||
const cfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri,
|
||||
mongoDatabase: 'stock',
|
||||
bypassSchemaValidation: malformed,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow(
|
||||
/cannot open a writable MongoDB connection to QA MongoDB/
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('allows non-QA multi-host dev seed lists and validates production multi-host URIs', () => {
|
||||
const devMultiHostUri =
|
||||
'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin';
|
||||
|
||||
const devIngestion = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: devMultiHostUri,
|
||||
mongoDatabase: 'stock_dev',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(devIngestion, 'dataIngestion', {})).not.toThrow();
|
||||
|
||||
const devPipeline = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: devMultiHostUri,
|
||||
mongoReadUri: devMultiHostUri,
|
||||
mongoReadOnly: false,
|
||||
mongoDatabase: 'stock_dev',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(devPipeline, 'dataPipeline', {})).not.toThrow();
|
||||
|
||||
const prodMultiHostSafe = makeConfig({
|
||||
environment: 'production',
|
||||
pgHost: 'pg.prod.internal',
|
||||
pgDatabase: 'trading_bot_prod',
|
||||
pgPassword: 'super-strong-prod-password',
|
||||
mongoUri: 'mongodb://prod:strongpass@mongo1.prod.internal:27017,mongo2.prod.internal:27017/stock',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(prodMultiHostSafe, 'webApi', {})).not.toThrow();
|
||||
|
||||
const prodMultiHostDevSecret = makeConfig({
|
||||
environment: 'production',
|
||||
pgHost: 'pg.prod.internal',
|
||||
pgDatabase: 'trading_bot_prod',
|
||||
pgPassword: 'super-strong-prod-password',
|
||||
mongoUri: 'mongodb://prod:trading_mongo_dev@mongo1.prod.internal:27017,mongo2.prod.internal:27017/stock',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(prodMultiHostDevSecret, 'webApi', {})).toThrow(
|
||||
/production MongoDB \(mongo1\.prod\.internal\) cannot use a default dev\/qa credential/
|
||||
);
|
||||
});
|
||||
|
||||
test('initializeStockConfig validates and guards multi-host MongoDB seed lists end-to-end', () => {
|
||||
const envKeys = [
|
||||
'NODE_ENV',
|
||||
'POSTGRES_HOST',
|
||||
'POSTGRES_PORT',
|
||||
'POSTGRES_DB',
|
||||
'POSTGRES_USER',
|
||||
'POSTGRES_PASSWORD',
|
||||
'MONGODB_URI',
|
||||
'MONGODB_READ_URI',
|
||||
'MONGODB_DATABASE',
|
||||
'HTTP_PROXY',
|
||||
'HTTPS_PROXY',
|
||||
'http_proxy',
|
||||
'https_proxy',
|
||||
] as const;
|
||||
const savedEnv: Partial<Record<(typeof envKeys)[number], string | undefined>> = {};
|
||||
for (const key of envKeys) {
|
||||
savedEnv[key] = process.env[key];
|
||||
}
|
||||
|
||||
try {
|
||||
process.env.NODE_ENV = 'development';
|
||||
process.env.POSTGRES_HOST = 'localhost';
|
||||
process.env.POSTGRES_PORT = '5433';
|
||||
process.env.POSTGRES_DB = 'trading_bot_dev';
|
||||
process.env.POSTGRES_USER = 'dev_user';
|
||||
process.env.POSTGRES_PASSWORD = 'dev_pass';
|
||||
process.env.MONGODB_URI =
|
||||
'mongodb://dev_admin:dev_mongo_pass@localhost:27018,127.0.0.1:27019/stock_dev?authSource=admin';
|
||||
process.env.MONGODB_READ_URI =
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock?authSource=stock';
|
||||
process.env.MONGODB_DATABASE = 'stock_dev';
|
||||
delete process.env.HTTP_PROXY;
|
||||
delete process.env.HTTPS_PROXY;
|
||||
delete process.env.http_proxy;
|
||||
delete process.env.https_proxy;
|
||||
|
||||
// Approved dev seed list passes schema validation and guard for dataIngestion
|
||||
resetStockConfig();
|
||||
const ingestionCfg = initializeStockConfig('dataIngestion');
|
||||
expect(ingestionCfg.database.mongodb.uri).toBe(process.env.MONGODB_URI);
|
||||
|
||||
// Approved QA read-only seed list passes schema validation and guard for dataPipeline
|
||||
resetStockConfig();
|
||||
const pipelineCfg = initializeStockConfig('dataPipeline', { mongoReadOnly: true });
|
||||
expect(pipelineCfg.database.mongodb.readUri).toBe(process.env.MONGODB_READ_URI);
|
||||
expect(pipelineCfg.database.mongodb.readOnly).toBe(true);
|
||||
|
||||
// Guarded QA seed list passes schema validation and is blocked by the safety guard
|
||||
process.env.MONGODB_URI =
|
||||
'mongodb://trading_admin:trading_mongo_dev@[::ffff:7f00:1]:27017/stock?authSource=admin';
|
||||
resetStockConfig();
|
||||
expect(() => initializeStockConfig('dataIngestion')).toThrow(
|
||||
/cannot open a writable MongoDB connection to QA MongoDB/
|
||||
);
|
||||
} finally {
|
||||
for (const key of envKeys) {
|
||||
if (savedEnv[key] === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = savedEnv[key];
|
||||
}
|
||||
}
|
||||
resetStockConfig();
|
||||
}
|
||||
});
|
||||
|
||||
test('blocks qa environment from targeting *_dev databases', () => {
|
||||
const cfg = makeConfig({
|
||||
environment: 'qa',
|
||||
|
|
@ -669,38 +397,4 @@ describe('MongoDBClient read-only enforcement', () => {
|
|||
await shutdown();
|
||||
}
|
||||
});
|
||||
|
||||
test('ServiceContainerBuilder extracts database from multi-host readUri when mongoReadOnly=true', async () => {
|
||||
const cfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: 'mongodb://dev_admin:dev_mongo_pass@localhost:27018/stock_dev?authSource=admin',
|
||||
mongoReadUri:
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017,localhost:27018/stock?authSource=stock',
|
||||
mongoDatabase: 'stock_dev',
|
||||
mongoReadOnly: true,
|
||||
});
|
||||
const { container, shutdown } = await new ServiceContainerBuilder()
|
||||
.withConfig(cfg)
|
||||
.withOptions({
|
||||
enableMongoDB: true,
|
||||
mongoReadOnly: true,
|
||||
enablePostgres: false,
|
||||
enableQuestDB: false,
|
||||
enableCache: false,
|
||||
enableQueue: false,
|
||||
enableBrowser: false,
|
||||
enableProxy: false,
|
||||
skipInitialization: true,
|
||||
})
|
||||
.buildOwned();
|
||||
|
||||
try {
|
||||
const mongo = container.resolve('mongoClient');
|
||||
expect(mongo).not.toBeNull();
|
||||
expect(mongo!.isReadOnly()).toBe(true);
|
||||
expect(mongo!.getDefaultDatabase()).toBe('stock');
|
||||
} finally {
|
||||
await shutdown();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,54 +0,0 @@
|
|||
import { readdirSync, readFileSync } from 'fs';
|
||||
import { join, relative } from 'path';
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
|
||||
// Guards T-16: all test files share one bun process, so process-global mocks in one
|
||||
// file silently change the modules and globals other files see. Restorable `spyOn`
|
||||
// is the supported pattern; child-process harnesses (test/integration) are exempt.
|
||||
const root = join(import.meta.dir, '..', '..');
|
||||
const scannedRoots = ['libs'];
|
||||
const forbidden: Array<{ label: string; pattern: RegExp }> = [
|
||||
{ label: 'mock.module(', pattern: /\bmock\.module\s*\(/ },
|
||||
{ label: 'Bun.serve assignment', pattern: /\bBun\.serve\s*=(?!=)/ },
|
||||
{ label: 'process.on assignment', pattern: /\bprocess\.(on|once|off)\s*=(?!=)/ },
|
||||
{ label: 'process.exit assignment', pattern: /\bprocess\.exit\s*=(?!=)/ },
|
||||
{ label: 'global console assignment', pattern: /\b(global|globalThis)\.console\s*=(?!=)/ },
|
||||
];
|
||||
|
||||
function collectTestFiles(dir: string, out: string[]): void {
|
||||
for (const entry of readdirSync(dir, { withFileTypes: true })) {
|
||||
if (entry.name === 'node_modules' || entry.name === 'dist' || entry.name.startsWith('.')) {
|
||||
continue;
|
||||
}
|
||||
const full = join(dir, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
collectTestFiles(full, out);
|
||||
} else if (/\.(test|spec)\.tsx?$/.test(entry.name)) {
|
||||
out.push(full);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
describe('in-process test isolation', () => {
|
||||
it('library tests never install process-global mocks or overwrite process/Bun globals', () => {
|
||||
const files: string[] = [];
|
||||
for (const dir of scannedRoots) {
|
||||
collectTestFiles(join(root, dir), files);
|
||||
}
|
||||
expect(files.length).toBeGreaterThan(0);
|
||||
|
||||
const violations: string[] = [];
|
||||
for (const file of files) {
|
||||
const lines = readFileSync(file, 'utf8').split('\n');
|
||||
lines.forEach((line, index) => {
|
||||
for (const { label, pattern } of forbidden) {
|
||||
if (pattern.test(line)) {
|
||||
violations.push(`${relative(root, file)}:${index + 1} ${label}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
expect(violations).toEqual([]);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue