T-7: M0.3a — Harden dev Mongo safety: env-safety throws on unsafe data-pipeline QA reads, scheduled jobs default off, read-only bypass tests
This commit is contained in:
commit
39f6f1fdfe
25 changed files with 3016 additions and 71 deletions
|
|
@ -79,7 +79,7 @@
|
|||
},
|
||||
"workers": 5,
|
||||
"concurrency": 2,
|
||||
"enableScheduledJobs": true,
|
||||
"enableScheduledJobs": false,
|
||||
"defaultJobOptions": {
|
||||
"attempts": 3,
|
||||
"backoff": {
|
||||
|
|
|
|||
|
|
@ -11,12 +11,18 @@ let configInstance: ConfigManager<StockAppConfig> | null = null;
|
|||
const __filename = fileURLToPath(import.meta.url);
|
||||
const __dirname = path.dirname(__filename);
|
||||
|
||||
export interface InitializeStockConfigOptions {
|
||||
mongoReadOnly?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize the stock application configuration
|
||||
* @param serviceName - Optional service name to override port configuration
|
||||
* @param options - Optional initialization overrides (e.g. mongoReadOnly)
|
||||
*/
|
||||
export function initializeStockConfig(
|
||||
serviceName?: StockServiceName
|
||||
serviceName?: StockServiceName,
|
||||
options?: InitializeStockConfigOptions
|
||||
): StockAppConfig {
|
||||
try {
|
||||
if (!configInstance) {
|
||||
|
|
@ -25,7 +31,20 @@ export function initializeStockConfig(
|
|||
});
|
||||
}
|
||||
|
||||
const config = configInstance.initialize(stockAppSchema);
|
||||
const rawConfig = configInstance.initialize(stockAppSchema);
|
||||
const config: StockAppConfig =
|
||||
options?.mongoReadOnly === true
|
||||
? {
|
||||
...rawConfig,
|
||||
database: {
|
||||
...rawConfig.database,
|
||||
mongodb: {
|
||||
...rawConfig.database.mongodb,
|
||||
readOnly: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
: rawConfig;
|
||||
assertEnvironmentSafety(config, serviceName);
|
||||
|
||||
// If a service name is provided, override the service port
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { StockAppConfig } from './schemas';
|
||||
|
||||
export type StockServiceName = 'dataIngestion' | 'dataPipeline' | 'webApi' | 'orchestrator';
|
||||
|
|
@ -17,7 +16,8 @@ function isLoopbackHost(host?: string): boolean {
|
|||
if (!host) {
|
||||
return false;
|
||||
}
|
||||
return LOOPBACK_HOSTS.has(host.toLowerCase());
|
||||
const normalized = host.replace(/^\[|\]$/g, '').toLowerCase();
|
||||
return LOOPBACK_HOSTS.has(normalized);
|
||||
}
|
||||
|
||||
function parseMongoTarget(uri?: string): {
|
||||
|
|
@ -44,10 +44,9 @@ function parseMongoTarget(uri?: string): {
|
|||
}
|
||||
}
|
||||
|
||||
function isQaMongoTarget(uri: string | undefined, fallbackDb?: string): boolean {
|
||||
function isQaMongoTarget(uri: string | undefined): boolean {
|
||||
const target = parseMongoTarget(uri);
|
||||
const db = target.database || fallbackDb;
|
||||
return isLoopbackHost(target.host) && target.port === 27017 && db === 'stock';
|
||||
return isLoopbackHost(target.host) && target.port === 27017;
|
||||
}
|
||||
|
||||
function isQaPostgresTarget(pg: StockAppConfig['database']['postgres']): boolean {
|
||||
|
|
@ -63,7 +62,6 @@ export function assertEnvironmentSafety(
|
|||
serviceName?: StockServiceName,
|
||||
env: Record<string, string | undefined> = process.env
|
||||
): void {
|
||||
const logger = getLogger('stock-config-safety');
|
||||
const environment = config.environment;
|
||||
|
||||
if (environment === 'test') {
|
||||
|
|
@ -86,19 +84,21 @@ export function assertEnvironmentSafety(
|
|||
const mongo = config.database.mongodb;
|
||||
if (mongo.enabled) {
|
||||
if (isReadOnlyPipeline) {
|
||||
const readTarget = parseMongoTarget(mongo.readUri ?? mongo.uri);
|
||||
const effectiveUri = mongo.readUri ?? mongo.uri;
|
||||
const readTarget = parseMongoTarget(effectiveUri);
|
||||
if (
|
||||
isQaMongoTarget(mongo.readUri ?? mongo.uri, mongo.database) &&
|
||||
readTarget.username === 'trading_admin'
|
||||
isQaMongoTarget(effectiveUri) &&
|
||||
(mongo.readOnly !== true || readTarget.username === 'trading_admin')
|
||||
) {
|
||||
logger.warn(
|
||||
'Development data-pipeline is reading QA MongoDB using admin credentials; ' +
|
||||
'configure MONGODB_READ_URI with the read-only user (studio_stock_bot_read) for defense in depth.'
|
||||
throw new Error(
|
||||
'Safety guard: development data-pipeline cannot read QA MongoDB (localhost:27017) ' +
|
||||
'with admin credentials or without read-only mode enabled. ' +
|
||||
'Configure MONGODB_READ_URI with the read-only user (studio_stock_bot_read) and enable mongoReadOnly: true.'
|
||||
);
|
||||
}
|
||||
} else if (
|
||||
!mongo.readOnly &&
|
||||
isQaMongoTarget(mongo.uri, mongo.database) &&
|
||||
isQaMongoTarget(mongo.uri) &&
|
||||
env.STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE !== 'true'
|
||||
) {
|
||||
throw new Error(
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ export {
|
|||
getProviderConfig,
|
||||
isFeatureEnabled,
|
||||
resetStockConfig,
|
||||
type InitializeStockConfigOptions,
|
||||
} from './config-instance';
|
||||
|
||||
// Export environment safety guard
|
||||
|
|
|
|||
|
|
@ -29,7 +29,7 @@ const app = new ServiceApplication(
|
|||
serviceName: 'data-ingestion',
|
||||
hostname: security.hostname,
|
||||
enableHandlers: true,
|
||||
enableScheduledJobs: config.queue?.enableScheduledJobs ?? true,
|
||||
enableScheduledJobs: config.queue?.enableScheduledJobs ?? false,
|
||||
corsConfig: {
|
||||
origin: '*',
|
||||
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
|
||||
|
|
@ -67,6 +67,7 @@ async function createContainer(baseConfig: import('@stock-bot/config').UnifiedAp
|
|||
enablePostgres: config.database?.postgres?.enabled ?? false,
|
||||
enableCache: true,
|
||||
enableQueue: true,
|
||||
delayWorkerStart: true,
|
||||
enableBrowser: true, // Data ingestion needs browser for web scraping
|
||||
enableProxy: true, // Data ingestion needs proxy for rate limiting
|
||||
})
|
||||
|
|
|
|||
|
|
@ -11,7 +11,7 @@ import { createRoutes } from './routes/create-routes';
|
|||
import { initializeAllHandlers } from './handlers';
|
||||
|
||||
// Initialize configuration with service-specific overrides
|
||||
const config = initializeStockConfig('dataPipeline');
|
||||
const config = initializeStockConfig('dataPipeline', { mongoReadOnly: true });
|
||||
const security = createHttpSecurity({ ...httpSecurityOptions(), environment: config.environment });
|
||||
|
||||
// Log the full configuration
|
||||
|
|
@ -29,7 +29,7 @@ const app = new ServiceApplication(
|
|||
serviceName: 'data-pipeline',
|
||||
hostname: security.hostname,
|
||||
enableHandlers: true,
|
||||
enableScheduledJobs: config.queue?.enableScheduledJobs ?? true,
|
||||
enableScheduledJobs: config.queue?.enableScheduledJobs ?? false,
|
||||
corsConfig: {
|
||||
origin: '*',
|
||||
allowMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH'],
|
||||
|
|
@ -70,6 +70,7 @@ async function createContainer(config: import('@stock-bot/config').UnifiedAppCon
|
|||
enablePostgres: true,
|
||||
enableCache: true,
|
||||
enableQueue: true,
|
||||
delayWorkerStart: true,
|
||||
enableBrowser: false, // Data pipeline doesn't need browser
|
||||
enableProxy: false, // Data pipeline doesn't need proxy
|
||||
skipInitialization: false, // Let builder handle initialization
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ export const queueConfigSchema = z.object({
|
|||
}),
|
||||
workers: z.number().default(1),
|
||||
concurrency: z.number().default(1),
|
||||
enableScheduledJobs: z.boolean().default(true),
|
||||
enableScheduledJobs: z.boolean().default(false),
|
||||
defaultJobOptions: z
|
||||
.object({
|
||||
attempts: z.number().default(3),
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ 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', () => ({
|
||||
|
|
@ -251,6 +252,22 @@ describe('EnvLoader', () => {
|
|||
});
|
||||
});
|
||||
|
||||
it('should map QUEUE_ENABLE_SCHEDULED_JOBS=true while defaulting unset to false in schema', () => {
|
||||
loader = new EnvLoader();
|
||||
const unsetConfig = loader.load();
|
||||
expect((unsetConfig.queue as Record<string, unknown> | undefined)?.enableScheduledJobs).toBeUndefined();
|
||||
expect(queueConfigSchema.parse({ redis: {}, ...(unsetConfig.queue as object) }).enableScheduledJobs).toBe(
|
||||
false
|
||||
);
|
||||
|
||||
process.env.QUEUE_ENABLE_SCHEDULED_JOBS = 'true';
|
||||
const optedInConfig = loader.load();
|
||||
expect((optedInConfig.queue as Record<string, unknown> | undefined)?.enableScheduledJobs).toBe(true);
|
||||
expect(
|
||||
queueConfigSchema.parse({ redis: {}, ...(optedInConfig.queue as object) }).enableScheduledJobs
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('should not apply provider mappings when prefix is set', () => {
|
||||
process.env.APP_WEBSHARE_API_KEY = 'key';
|
||||
|
||||
|
|
|
|||
|
|
@ -214,7 +214,7 @@ describe('Config Schemas', () => {
|
|||
},
|
||||
workers: 1,
|
||||
concurrency: 1,
|
||||
enableScheduledJobs: true,
|
||||
enableScheduledJobs: false,
|
||||
defaultJobOptions: {
|
||||
attempts: 3,
|
||||
backoff: {
|
||||
|
|
@ -253,6 +253,12 @@ describe('Config Schemas', () => {
|
|||
|
||||
const config = queueConfigSchema.parse(input);
|
||||
expect(config).toEqual(input);
|
||||
|
||||
const optedIn = queueConfigSchema.parse({
|
||||
redis: {},
|
||||
enableScheduledJobs: true,
|
||||
});
|
||||
expect(optedIn.enableScheduledJobs).toBe(true);
|
||||
});
|
||||
|
||||
it('should validate backoff type', () => {
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ export const queueConfigSchema = z.object({
|
|||
enabled: z.boolean().optional().default(true),
|
||||
workers: z.number().optional().default(1),
|
||||
concurrency: z.number().optional().default(1),
|
||||
enableScheduledJobs: z.boolean().optional().default(true),
|
||||
enableScheduledJobs: z.boolean().optional().default(false),
|
||||
defaultJobOptions: z
|
||||
.object({
|
||||
attempts: z.number().default(3),
|
||||
|
|
|
|||
|
|
@ -9,6 +9,7 @@ import {
|
|||
import type { BaseAppConfig as StockBotAppConfig, UnifiedAppConfig } from '@stock-bot/config';
|
||||
import { toUnifiedConfig } from '@stock-bot/config';
|
||||
import { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||
import type { QueueManagerDependencies } from '@stock-bot/queue';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import { appConfigSchema, type AppConfig } from '../config/schemas';
|
||||
import {
|
||||
|
|
@ -53,6 +54,7 @@ export class ServiceContainerBuilder {
|
|||
private config: Partial<AppConfig> = {};
|
||||
private unifiedConfig: UnifiedAppConfig | null = null;
|
||||
private customRegistrations: ContainerRegistrar[] = [];
|
||||
private readonly deps?: { queueManagerDeps?: QueueManagerDependencies };
|
||||
private options: ContainerBuildOptions = {
|
||||
enableCache: true,
|
||||
enableQueue: true,
|
||||
|
|
@ -65,6 +67,10 @@ export class ServiceContainerBuilder {
|
|||
initializationTimeout: 30000,
|
||||
};
|
||||
|
||||
constructor(deps?: { queueManagerDeps?: QueueManagerDependencies }) {
|
||||
this.deps = deps;
|
||||
}
|
||||
|
||||
withConfig(config: AppConfig | StockBotAppConfig | UnifiedAppConfig): this {
|
||||
// Convert to unified config format
|
||||
this.unifiedConfig = toUnifiedConfig(config);
|
||||
|
|
@ -209,7 +215,7 @@ export class ServiceContainerBuilder {
|
|||
enabled: true,
|
||||
workers: 1,
|
||||
concurrency: 1,
|
||||
enableScheduledJobs: true,
|
||||
enableScheduledJobs: false,
|
||||
defaultJobOptions: {
|
||||
attempts: 3,
|
||||
backoff: { type: 'exponential' as const, delay: 1000 },
|
||||
|
|
@ -240,7 +246,10 @@ export class ServiceContainerBuilder {
|
|||
registerCoreServices(container, config);
|
||||
registerCacheServices(container, config);
|
||||
registerDatabaseServices(container, config);
|
||||
registerApplicationServices(container, config);
|
||||
registerApplicationServices(container, config, {
|
||||
delayWorkerStart: this.options.delayWorkerStart ?? false,
|
||||
queueManagerDeps: this.deps?.queueManagerDeps,
|
||||
});
|
||||
|
||||
// Register service container aggregate
|
||||
container.register({
|
||||
|
|
|
|||
|
|
@ -39,6 +39,7 @@ export interface ServiceContainerOptions {
|
|||
enablePostgres?: boolean;
|
||||
enableCache?: boolean;
|
||||
enableQueue?: boolean;
|
||||
delayWorkerStart?: boolean;
|
||||
enableBrowser?: boolean;
|
||||
enableProxy?: boolean;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -2,13 +2,17 @@ import { asFunction, asValue, type AwilixContainer } from 'awilix';
|
|||
import { createCache } from '@stock-bot/cache';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { ProxyManager } from '@stock-bot/proxy';
|
||||
import { QueueManager } from '@stock-bot/queue';
|
||||
import { QueueManager, type QueueManagerDependencies } from '@stock-bot/queue';
|
||||
import type { AppConfig } from '../config/schemas';
|
||||
import type { ServiceDefinitions } from '../container/types';
|
||||
|
||||
export function registerApplicationServices(
|
||||
container: AwilixContainer<ServiceDefinitions>,
|
||||
config: AppConfig
|
||||
config: AppConfig,
|
||||
options?: {
|
||||
delayWorkerStart?: boolean;
|
||||
queueManagerDeps?: QueueManagerDependencies;
|
||||
}
|
||||
): void {
|
||||
// Browser is an ingestion-only capability registered by apps/stock/data-ingestion
|
||||
// via ServiceContainerBuilder.withRegistrations() so non-ingestion apps never pull Playwright.
|
||||
|
|
@ -72,11 +76,12 @@ export function registerApplicationServices(
|
|||
concurrency: defined(config.queue).concurrency ?? 1,
|
||||
defaultJobOptions: defined(config.queue).defaultJobOptions,
|
||||
},
|
||||
enableScheduledJobs: defined(config.queue).enableScheduledJobs ?? true,
|
||||
enableScheduledJobs: defined(config.queue).enableScheduledJobs ?? false,
|
||||
delayWorkerStart: options?.delayWorkerStart ?? false,
|
||||
autoDiscoverHandlers: true,
|
||||
};
|
||||
|
||||
return new QueueManager(queueConfig, handlerRegistry, logger);
|
||||
return new QueueManager(queueConfig, handlerRegistry, logger, options?.queueManagerDeps);
|
||||
}).singleton(),
|
||||
});
|
||||
} else {
|
||||
|
|
|
|||
|
|
@ -441,15 +441,11 @@ export class ServiceApplication {
|
|||
|
||||
// Initialize scheduled jobs if enabled in both serviceConfig and runtime queue config
|
||||
const scheduledJobsEnabled =
|
||||
this.serviceConfig.enableScheduledJobs && (this.config.queue?.enableScheduledJobs ?? true);
|
||||
this.serviceConfig.enableScheduledJobs && (this.config.queue?.enableScheduledJobs ?? false);
|
||||
if (scheduledJobsEnabled) {
|
||||
await this.initializeScheduledJobs();
|
||||
} else {
|
||||
const queueManager = this.resolveOptional('queueManager');
|
||||
if (queueManager?.startAllWorkers) {
|
||||
queueManager.startAllWorkers();
|
||||
this.logger.info('Queue workers started (scheduled cron jobs disabled)');
|
||||
}
|
||||
await this.disableScheduledJobs();
|
||||
}
|
||||
|
||||
// Call before start hook
|
||||
|
|
@ -487,6 +483,56 @@ export class ServiceApplication {
|
|||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile and remove this service's persisted scheduled jobs before starting workers
|
||||
* when scheduled jobs are disabled.
|
||||
*/
|
||||
private async disableScheduledJobs(): Promise<void> {
|
||||
const queueManager = this.resolveOptional('queueManager');
|
||||
if (!queueManager) {
|
||||
return;
|
||||
}
|
||||
|
||||
const handlerRegistry = this.resolveOptional('handlerRegistry');
|
||||
const ownedHandlers = new Set<string>();
|
||||
const currentService = this.config.service.serviceName;
|
||||
|
||||
if (handlerRegistry) {
|
||||
if (typeof handlerRegistry.getAllHandlersWithSchedule === 'function') {
|
||||
for (const [handlerName] of handlerRegistry.getAllHandlersWithSchedule()) {
|
||||
const ownerService =
|
||||
typeof handlerRegistry.getHandlerService === 'function'
|
||||
? handlerRegistry.getHandlerService(handlerName)
|
||||
: undefined;
|
||||
if (!ownerService || ownerService === currentService) {
|
||||
ownedHandlers.add(handlerName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (currentService && typeof handlerRegistry.getServiceHandlers === 'function') {
|
||||
for (const metadata of handlerRegistry.getServiceHandlers(currentService)) {
|
||||
ownedHandlers.add(metadata.name);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof queueManager.getQueueNames === 'function') {
|
||||
for (const queueName of queueManager.getQueueNames()) {
|
||||
ownedHandlers.add(queueName);
|
||||
}
|
||||
}
|
||||
|
||||
if (ownedHandlers.size > 0 && typeof queueManager.removeScheduledJobsForQueues === 'function') {
|
||||
await queueManager.removeScheduledJobsForQueues(Array.from(ownedHandlers));
|
||||
}
|
||||
|
||||
if (queueManager.startAllWorkers) {
|
||||
queueManager.startAllWorkers();
|
||||
this.logger.info('Queue workers started (scheduled cron jobs disabled)');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize scheduled jobs from handler registry
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { describe, expect, it } from 'bun:test';
|
||||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import { ZodError } from 'zod';
|
||||
import { baseAppSchema } from '@stock-bot/config';
|
||||
import type { Queue, QueueWorkerConfig } from '@stock-bot/queue';
|
||||
import { ServiceContainerBuilder } from '../src/container/builder';
|
||||
|
||||
// Production schemas and registrations, with initialization disabled: no module
|
||||
|
|
@ -130,4 +131,119 @@ describe('ServiceContainerBuilder production configuration', () => {
|
|||
new ServiceContainerBuilder().withConfig({ service: { name: 'incomplete' } } as never)
|
||||
).toThrow(ZodError);
|
||||
});
|
||||
|
||||
it('defaults delayWorkerStart to false for orchestrator-style containers and enables it only when opted in', async () => {
|
||||
const queueEnabledConfig = {
|
||||
...configuration(),
|
||||
service: { name: 'orchestrator', port: 3003 },
|
||||
redis: { enabled: true, host: '127.0.0.1', port: 16379, db: 0 },
|
||||
queue: {
|
||||
enabled: true,
|
||||
workers: 1,
|
||||
concurrency: 1,
|
||||
redis: { host: '127.0.0.1', port: 16379, db: 0 },
|
||||
},
|
||||
};
|
||||
|
||||
const createOfflineQueueDeps = () => {
|
||||
const redisQuit = mock(async () => 'OK');
|
||||
const createdQueues: Array<{
|
||||
name: string;
|
||||
workerConfig: QueueWorkerConfig;
|
||||
close: ReturnType<typeof mock>;
|
||||
}> = [];
|
||||
const createRedis = mock(() => ({ quit: redisQuit, disconnect: mock(() => {}) }) as any);
|
||||
const createQueue = mock(
|
||||
(
|
||||
name: string,
|
||||
_redisConfig: unknown,
|
||||
_defaultJobOptions: unknown,
|
||||
workerConfig: QueueWorkerConfig
|
||||
) => {
|
||||
const workerCount = workerConfig.startWorker ? (workerConfig.workers ?? 0) : 0;
|
||||
const close = mock(async () => {});
|
||||
createdQueues.push({ name, workerConfig, close });
|
||||
return {
|
||||
getName: () => name,
|
||||
getWorkerCount: () => workerCount,
|
||||
close,
|
||||
} as unknown as Queue;
|
||||
}
|
||||
);
|
||||
return { deps: { createRedis, createQueue }, createdQueues, redisQuit };
|
||||
};
|
||||
|
||||
// Orchestrator path (matching apps/stock/orchestrator/src/simple-container.ts): no delayWorkerStart
|
||||
const orchestratorStubs = createOfflineQueueDeps();
|
||||
const orchestratorContainer = await new ServiceContainerBuilder({
|
||||
queueManagerDeps: orchestratorStubs.deps,
|
||||
})
|
||||
.withConfig(queueEnabledConfig)
|
||||
.withOptions({
|
||||
enableMongoDB: false,
|
||||
enablePostgres: false,
|
||||
enableCache: true,
|
||||
enableQueue: true,
|
||||
enableQuestDB: false,
|
||||
enableBrowser: false,
|
||||
enableProxy: false,
|
||||
})
|
||||
.skipInitialization()
|
||||
.build();
|
||||
|
||||
const orchestratorQueueManager = orchestratorContainer.resolve('queueManager');
|
||||
try {
|
||||
expect(orchestratorQueueManager).not.toBeNull();
|
||||
expect(orchestratorQueueManager!.getConfig().delayWorkerStart).toBe(false);
|
||||
|
||||
const queue = orchestratorQueueManager!.getQueue('orchestrator', {
|
||||
workers: 1,
|
||||
concurrency: 3,
|
||||
});
|
||||
expect(orchestratorStubs.createdQueues).toHaveLength(1);
|
||||
expect(orchestratorStubs.createdQueues[0]?.workerConfig.startWorker).toBe(true);
|
||||
expect(orchestratorStubs.createdQueues[0]?.workerConfig.workers).toBe(1);
|
||||
expect(orchestratorStubs.createdQueues[0]?.workerConfig.concurrency).toBe(3);
|
||||
expect(queue.getWorkerCount()).toBe(1);
|
||||
} finally {
|
||||
await orchestratorQueueManager?.shutdown();
|
||||
await orchestratorContainer.dispose();
|
||||
}
|
||||
|
||||
// Opt-in path (matching data-ingestion / data-pipeline): delayWorkerStart: true
|
||||
const delayedStubs = createOfflineQueueDeps();
|
||||
const delayedContainer = await new ServiceContainerBuilder({
|
||||
queueManagerDeps: delayedStubs.deps,
|
||||
})
|
||||
.withConfig({
|
||||
...queueEnabledConfig,
|
||||
service: { name: 'data-ingestion', port: 3001 },
|
||||
})
|
||||
.withOptions({
|
||||
enableMongoDB: false,
|
||||
enablePostgres: false,
|
||||
enableCache: true,
|
||||
enableQueue: true,
|
||||
delayWorkerStart: true,
|
||||
enableQuestDB: false,
|
||||
enableBrowser: false,
|
||||
enableProxy: false,
|
||||
})
|
||||
.skipInitialization()
|
||||
.build();
|
||||
|
||||
const delayedQueueManager = delayedContainer.resolve('queueManager');
|
||||
try {
|
||||
expect(delayedQueueManager).not.toBeNull();
|
||||
expect(delayedQueueManager!.getConfig().delayWorkerStart).toBe(true);
|
||||
|
||||
const queue = delayedQueueManager!.getQueue('te');
|
||||
expect(delayedStubs.createdQueues).toHaveLength(1);
|
||||
expect(delayedStubs.createdQueues[0]?.workerConfig.startWorker).toBe(false);
|
||||
expect(queue.getWorkerCount()).toBe(0);
|
||||
} finally {
|
||||
await delayedQueueManager?.shutdown();
|
||||
await delayedContainer.dispose();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -366,7 +366,18 @@ describe('ServiceApplication', () => {
|
|||
|
||||
const jobContainerFactory = mock(async () => containerWithJobs);
|
||||
|
||||
app = new ServiceApplication(mockConfig, serviceConfig);
|
||||
const configWithScheduledJobs = {
|
||||
...mockConfig,
|
||||
queue: {
|
||||
enabled: true,
|
||||
redis: { host: 'localhost', port: 6379, db: 1 },
|
||||
workers: 1,
|
||||
concurrency: 1,
|
||||
enableScheduledJobs: true,
|
||||
},
|
||||
};
|
||||
|
||||
app = new ServiceApplication(configWithScheduledJobs as any, serviceConfig);
|
||||
|
||||
await app.start(jobContainerFactory, mockRouteFactory);
|
||||
|
||||
|
|
@ -382,6 +393,214 @@ describe('ServiceApplication', () => {
|
|||
expect(mockQueueManager.startAllWorkers).toHaveBeenCalled();
|
||||
expect(mockLogger.info).toHaveBeenCalledWith('Scheduled jobs created', { totalJobs: 1 });
|
||||
});
|
||||
|
||||
it('should reconcile owned repeat schedules before starting workers when scheduling is disabled while preserving manual jobs and other services', async () => {
|
||||
const serviceConfig: ServiceApplicationConfig = {
|
||||
serviceName: 'test-service',
|
||||
enableScheduledJobs: true,
|
||||
};
|
||||
|
||||
for (const runtimeConfig of [
|
||||
mockConfig,
|
||||
{
|
||||
...mockConfig,
|
||||
queue: {
|
||||
enabled: true,
|
||||
redis: { host: 'localhost', port: 6379, db: 1 },
|
||||
workers: 1,
|
||||
concurrency: 1,
|
||||
enableScheduledJobs: false,
|
||||
},
|
||||
},
|
||||
]) {
|
||||
// Simulated shared queue store persisted across restarts
|
||||
const repeatSchedules = new Map<string, string[]>([
|
||||
['{test-service_eod}', ['{test-service_eod}:crawl']],
|
||||
['{other-service_sync}', ['{other-service_sync}:daily']],
|
||||
]);
|
||||
const queuedJobs = new Map<string, Array<{ id: string; repeatJobKey?: string }>>([
|
||||
[
|
||||
'{test-service_eod}',
|
||||
[
|
||||
{ id: 'repeat-1', repeatJobKey: '{test-service_eod}:crawl' },
|
||||
{ id: 'manual-1' },
|
||||
],
|
||||
],
|
||||
[
|
||||
'{other-service_sync}',
|
||||
[{ id: 'other-repeat-1', repeatJobKey: '{other-service_sync}:daily' }],
|
||||
],
|
||||
]);
|
||||
const callOrder: string[] = [];
|
||||
|
||||
const mockHandlerRegistry = {
|
||||
getAllHandlersWithSchedule: () =>
|
||||
new Map([
|
||||
['eod', { scheduledJobs: [{ operation: 'crawl', cronPattern: '0 * * * *' }] }],
|
||||
['sync', { scheduledJobs: [{ operation: 'daily', cronPattern: '0 0 * * *' }] }],
|
||||
]),
|
||||
getHandlerService: (handlerName: string) =>
|
||||
handlerName === 'eod' ? 'test-service' : 'other-service',
|
||||
getServiceHandlers: (svc: string) =>
|
||||
svc === 'test-service' ? [{ name: 'eod' }] : [{ name: 'sync' }],
|
||||
};
|
||||
|
||||
const mockQueue = {
|
||||
addScheduledJob: mock(() => Promise.resolve()),
|
||||
};
|
||||
|
||||
const mockQueueManager = {
|
||||
getQueue: mock(() => mockQueue),
|
||||
removeScheduledJobsForQueues: mock(async (handlers: string[]) => {
|
||||
callOrder.push(`reconcile:${handlers.join(',')}`);
|
||||
for (const handler of handlers) {
|
||||
const fullName = `{test-service_${handler}}`;
|
||||
repeatSchedules.delete(fullName);
|
||||
const existing = queuedJobs.get(fullName) ?? [];
|
||||
queuedJobs.set(
|
||||
fullName,
|
||||
existing.filter(job => !job.repeatJobKey)
|
||||
);
|
||||
}
|
||||
return handlers.length;
|
||||
}),
|
||||
startAllWorkers: mock(() => {
|
||||
callOrder.push('startAllWorkers');
|
||||
}),
|
||||
shutdown: mock(() => Promise.resolve()),
|
||||
};
|
||||
|
||||
const containerWithJobs = {
|
||||
resolve: mock((name: string) => {
|
||||
if (name === 'serviceContainer') {
|
||||
return { test: 'container' };
|
||||
}
|
||||
if (name === 'handlerRegistry') {
|
||||
return mockHandlerRegistry;
|
||||
}
|
||||
if (name === 'queueManager') {
|
||||
return mockQueueManager;
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
};
|
||||
|
||||
app = new ServiceApplication(runtimeConfig as any, serviceConfig);
|
||||
await app.start(async () => containerWithJobs as any, mockRouteFactory);
|
||||
|
||||
expect(mockQueueManager.getQueue).not.toHaveBeenCalled();
|
||||
expect(mockQueue.addScheduledJob).not.toHaveBeenCalled();
|
||||
expect(mockQueueManager.removeScheduledJobsForQueues).toHaveBeenCalledWith(['eod']);
|
||||
expect(mockQueueManager.startAllWorkers).toHaveBeenCalledTimes(1);
|
||||
// Reconciliation must complete before workers start consuming jobs
|
||||
expect(callOrder).toEqual(['reconcile:eod', 'startAllWorkers']);
|
||||
// Own repeat schedule & repeat-spawned job cleared; manual job & other service preserved
|
||||
expect(repeatSchedules.has('{test-service_eod}')).toBe(false);
|
||||
expect(queuedJobs.get('{test-service_eod}')).toEqual([{ id: 'manual-1' }]);
|
||||
expect(repeatSchedules.get('{other-service_sync}')).toEqual([
|
||||
'{other-service_sync}:daily',
|
||||
]);
|
||||
expect(queuedJobs.get('{other-service_sync}')).toEqual([
|
||||
{ id: 'other-repeat-1', repeatJobKey: '{other-service_sync}:daily' },
|
||||
]);
|
||||
}
|
||||
});
|
||||
|
||||
it('keeps handler-opened queues workerless through handler initialization and schedule reconciliation before starting workers', async () => {
|
||||
const serviceConfig: ServiceApplicationConfig = {
|
||||
serviceName: 'data-ingestion',
|
||||
enableHandlers: true,
|
||||
enableScheduledJobs: false,
|
||||
};
|
||||
|
||||
const callOrder: string[] = [];
|
||||
let teWorkersActive = false;
|
||||
const openedQueues: string[] = [];
|
||||
|
||||
const mockHandlerRegistry = {
|
||||
getAllMetadata: () => new Map(),
|
||||
getAllHandlersWithSchedule: () =>
|
||||
new Map([
|
||||
['te', { scheduledJobs: [{ operation: 'crawlScheduler', cronPattern: '0 6 * * *' }] }],
|
||||
]),
|
||||
getHandlerService: () => 'data-ingestion',
|
||||
getServiceHandlers: () => [{ name: 'te' }],
|
||||
};
|
||||
|
||||
const mockQueueManager = {
|
||||
getQueue: mock((name: string) => {
|
||||
openedQueues.push(`{data-ingestion_${name}}`);
|
||||
callOrder.push(`getQueue:${name}:workers=${teWorkersActive}`);
|
||||
return {
|
||||
getName: () => `{data-ingestion_${name}}`,
|
||||
getWorkerCount: () => (teWorkersActive ? 1 : 0),
|
||||
};
|
||||
}),
|
||||
getQueueNames: mock(() => [...openedQueues]),
|
||||
removeScheduledJobsForQueues: mock(async (queues: string[]) => {
|
||||
// Workers must STILL be inactive while reconciliation runs
|
||||
expect(teWorkersActive).toBe(false);
|
||||
callOrder.push(`reconcile:${queues.join(',')}:workers=${teWorkersActive}`);
|
||||
return 1;
|
||||
}),
|
||||
startAllWorkers: mock(() => {
|
||||
teWorkersActive = true;
|
||||
callOrder.push(`startAllWorkers:workers=${teWorkersActive}`);
|
||||
}),
|
||||
shutdown: mock(() => Promise.resolve()),
|
||||
};
|
||||
|
||||
const containerWithTeHandler = {
|
||||
resolve: mock((name: string) => {
|
||||
if (name === 'serviceContainer') {
|
||||
return { queueManager: mockQueueManager };
|
||||
}
|
||||
if (name === 'handlerScanner') {
|
||||
return {};
|
||||
}
|
||||
if (name === 'handlerRegistry') {
|
||||
return mockHandlerRegistry;
|
||||
}
|
||||
if (name === 'queueManager') {
|
||||
return mockQueueManager;
|
||||
}
|
||||
return null;
|
||||
}),
|
||||
};
|
||||
|
||||
// Simulate TeHandler constructor opening its owned queue during handlerInitializer
|
||||
const handlerInitializer = mock(async (services: any) => {
|
||||
const teQueue = services.queueManager.getQueue('te');
|
||||
expect(teQueue.getWorkerCount()).toBe(0);
|
||||
});
|
||||
|
||||
app = new ServiceApplication(
|
||||
{
|
||||
...mockConfig,
|
||||
service: { ...mockConfig.service, name: 'data-ingestion', serviceName: 'data-ingestion' },
|
||||
queue: {
|
||||
enabled: true,
|
||||
redis: { host: 'localhost', port: 6379, db: 0 },
|
||||
workers: 1,
|
||||
concurrency: 1,
|
||||
enableScheduledJobs: false,
|
||||
},
|
||||
} as any,
|
||||
serviceConfig
|
||||
);
|
||||
|
||||
await app.start(
|
||||
async () => containerWithTeHandler as any,
|
||||
mockRouteFactory,
|
||||
handlerInitializer
|
||||
);
|
||||
|
||||
expect(callOrder).toEqual([
|
||||
'getQueue:te:workers=false',
|
||||
'reconcile:te,{data-ingestion_te}:workers=false',
|
||||
'startAllWorkers:workers=true',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('stop method', () => {
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
export { Queue } from './queue';
|
||||
export { QueueManager } from './queue-manager';
|
||||
export { QueueManager, type QueueManagerDependencies } from './queue-manager';
|
||||
export { ServiceCache, createServiceCache } from './service-cache';
|
||||
export {
|
||||
normalizeServiceName,
|
||||
|
|
|
|||
|
|
@ -1,14 +1,18 @@
|
|||
import { Queue as BullQueue, type Job } from 'bullmq';
|
||||
import Redis from 'ioredis';
|
||||
import Redis, { type RedisOptions } from 'ioredis';
|
||||
import type { CacheProvider } from '@stock-bot/cache';
|
||||
import { createCache } from '@stock-bot/cache';
|
||||
import type { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||
import { defined } from '@stock-bot/invariants';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import type { LoggerLike as Logger } from '@stock-bot/logger';
|
||||
import { Queue, type QueueWorkerConfig } from './queue';
|
||||
import {
|
||||
Queue,
|
||||
removeScheduledJobsFromBullQueue,
|
||||
type QueueWorkerConfig,
|
||||
} from './queue';
|
||||
import { QueueRateLimiter } from './rate-limiter';
|
||||
import { getFullQueueName, parseQueueName } from './service-utils';
|
||||
import { getFullQueueName, normalizeServiceName, parseQueueName } from './service-utils';
|
||||
import type {
|
||||
GlobalStats,
|
||||
JobData,
|
||||
|
|
@ -18,9 +22,21 @@ import type {
|
|||
QueueRoute,
|
||||
QueueStats,
|
||||
RateLimitRule,
|
||||
RedisConfig,
|
||||
} from './types';
|
||||
import { getRedisConnection } from './utils';
|
||||
|
||||
export interface QueueManagerDependencies {
|
||||
createRedis?: (options: RedisOptions) => Redis;
|
||||
createQueue?: (
|
||||
name: string,
|
||||
redisConfig: RedisConfig,
|
||||
defaultJobOptions: JobOptions,
|
||||
workerConfig: QueueWorkerConfig,
|
||||
logger: Logger
|
||||
) => Queue;
|
||||
}
|
||||
|
||||
/**
|
||||
* QueueManager provides unified queue and cache management with service discovery
|
||||
* Handles both local and cross-service queue operations
|
||||
|
|
@ -32,9 +48,11 @@ export class QueueManager {
|
|||
private redisConnection: ReturnType<typeof getRedisConnection>;
|
||||
private ioredisConnection?: Redis;
|
||||
private lifecycle: 'running' | 'draining' | 'closed' = 'running';
|
||||
private workersStarted = false;
|
||||
private shutdownPromise: Promise<void> | null = null;
|
||||
private config: QueueManagerConfig;
|
||||
private readonly logger: Logger;
|
||||
private readonly deps?: QueueManagerDependencies;
|
||||
|
||||
// Service discovery features
|
||||
private serviceName?: string;
|
||||
|
|
@ -42,7 +60,12 @@ export class QueueManager {
|
|||
private producerQueues = new Map<string, BullQueue>(); // For cross-service sending
|
||||
private handlerRegistry?: HandlerRegistry;
|
||||
|
||||
constructor(config: QueueManagerConfig, handlerRegistry?: HandlerRegistry, logger?: Logger) {
|
||||
constructor(
|
||||
config: QueueManagerConfig,
|
||||
handlerRegistry?: HandlerRegistry,
|
||||
logger?: Logger,
|
||||
deps?: QueueManagerDependencies
|
||||
) {
|
||||
// Always use DB 0 for queues if service name is provided
|
||||
if (config.serviceName) {
|
||||
config = {
|
||||
|
|
@ -58,11 +81,12 @@ export class QueueManager {
|
|||
this.serviceName = config.serviceName;
|
||||
this.handlerRegistry = handlerRegistry;
|
||||
this.logger = logger || getLogger('QueueManager');
|
||||
this.deps = deps;
|
||||
this.redisConnection = getRedisConnection(config.redis);
|
||||
|
||||
// Create ioredis connection for rate limiter
|
||||
const retryDelay = config.redis.retryDelay;
|
||||
this.ioredisConnection = new Redis({
|
||||
const ioredisOptions = {
|
||||
host: config.redis.host,
|
||||
port: config.redis.port,
|
||||
password: config.redis.password,
|
||||
|
|
@ -71,7 +95,10 @@ export class QueueManager {
|
|||
maxRetriesPerRequest: config.redis.maxRetriesPerRequest ?? 3,
|
||||
...(retryDelay === undefined ? {} : { retryStrategy: () => retryDelay }),
|
||||
enableReadyCheck: true,
|
||||
});
|
||||
};
|
||||
this.ioredisConnection = deps?.createRedis
|
||||
? deps.createRedis(ioredisOptions)
|
||||
: new Redis(ioredisOptions);
|
||||
|
||||
// Rate limiter will be initialized when rules are added dynamically
|
||||
// No longer initialized from config
|
||||
|
|
@ -150,23 +177,33 @@ export class QueueManager {
|
|||
const workers = mergedOptions.workers ?? this.config.defaultQueueOptions?.workers ?? 1;
|
||||
const concurrency =
|
||||
mergedOptions.concurrency ?? this.config.defaultQueueOptions?.concurrency ?? 1;
|
||||
const shouldStartWorker =
|
||||
workers > 0 && (!this.config.delayWorkerStart || this.workersStarted);
|
||||
|
||||
const queueConfig: QueueWorkerConfig = {
|
||||
workers,
|
||||
concurrency,
|
||||
startWorker: workers > 0,
|
||||
startWorker: shouldStartWorker,
|
||||
handlerRegistry: options.handlerRegistry || this.handlerRegistry,
|
||||
serviceName: this.config.serviceName,
|
||||
queueManager: this,
|
||||
};
|
||||
|
||||
const queue = new Queue(
|
||||
queueName,
|
||||
this.config.redis,
|
||||
mergedOptions.defaultJobOptions || {},
|
||||
queueConfig,
|
||||
this.logger
|
||||
);
|
||||
const queue = this.deps?.createQueue
|
||||
? this.deps.createQueue(
|
||||
queueName,
|
||||
this.config.redis,
|
||||
mergedOptions.defaultJobOptions || {},
|
||||
queueConfig,
|
||||
this.logger
|
||||
)
|
||||
: new Queue(
|
||||
queueName,
|
||||
this.config.redis,
|
||||
mergedOptions.defaultJobOptions || {},
|
||||
queueConfig,
|
||||
this.logger
|
||||
);
|
||||
|
||||
// Store the queue
|
||||
this.queues.set(queueName, queue);
|
||||
|
|
@ -179,7 +216,7 @@ export class QueueManager {
|
|||
workers: workers,
|
||||
concurrency: concurrency,
|
||||
handlerRegistryProvided: !!this.handlerRegistry,
|
||||
willStartWorkers: workers > 0,
|
||||
willStartWorkers: shouldStartWorker,
|
||||
isOwnQueue,
|
||||
serviceName: this.serviceName,
|
||||
});
|
||||
|
|
@ -515,8 +552,12 @@ export class QueueManager {
|
|||
if (this.lifecycle !== 'running') {
|
||||
throw new Error('QueueManager is shutting down; workers cannot be started');
|
||||
}
|
||||
this.workersStarted = true;
|
||||
let workersStarted = 0;
|
||||
const queues = this.queues;
|
||||
const normalizedService = this.serviceName
|
||||
? normalizeServiceName(this.serviceName)
|
||||
: undefined;
|
||||
|
||||
this.logger.info(
|
||||
`Starting workers for ${queues.size} queues: ${Array.from(queues.keys()).join(', ')} (service: ${this.serviceName})`
|
||||
|
|
@ -527,7 +568,7 @@ export class QueueManager {
|
|||
if (this.serviceName) {
|
||||
const parsed = parseQueueName(queueName);
|
||||
// Skip if not our service's queue
|
||||
if (parsed && parsed.service !== this.serviceName) {
|
||||
if (parsed && parsed.service !== this.serviceName && parsed.service !== normalizedService) {
|
||||
this.logger.trace('Skipping workers for cross-service queue', {
|
||||
queueName,
|
||||
ownerService: parsed.service,
|
||||
|
|
@ -558,6 +599,72 @@ export class QueueManager {
|
|||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Reconcile and remove persisted repeatable/scheduled jobs for the specified
|
||||
* handler queues owned by this service without starting workers.
|
||||
* Manual jobs and other services' queues are preserved.
|
||||
*/
|
||||
async removeScheduledJobsForQueues(queueNames: string[]): Promise<number> {
|
||||
this.assertConnectionsOpen();
|
||||
let totalRemoved = 0;
|
||||
const seenFullNames = new Set<string>();
|
||||
const normalizedService = this.serviceName
|
||||
? normalizeServiceName(this.serviceName)
|
||||
: undefined;
|
||||
|
||||
for (const rawQueueName of queueNames) {
|
||||
let fullQueueName = rawQueueName;
|
||||
let isOwnQueue = true;
|
||||
|
||||
if (this.serviceName) {
|
||||
const parsed = parseQueueName(rawQueueName);
|
||||
if (parsed) {
|
||||
fullQueueName = rawQueueName;
|
||||
isOwnQueue =
|
||||
parsed.service === this.serviceName || parsed.service === normalizedService;
|
||||
} else {
|
||||
fullQueueName = getFullQueueName(this.serviceName, rawQueueName);
|
||||
isOwnQueue = true;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isOwnQueue || seenFullNames.has(fullQueueName)) {
|
||||
continue;
|
||||
}
|
||||
seenFullNames.add(fullQueueName);
|
||||
|
||||
const existingQueue = this.queues.get(fullQueueName);
|
||||
if (existingQueue) {
|
||||
totalRemoved += await existingQueue.removeAllScheduledJobs();
|
||||
continue;
|
||||
}
|
||||
|
||||
// Open a workerless BullQueue handle to clear persisted repeat schedules
|
||||
// before any worker can consume stale repeat jobs.
|
||||
const tempQueue = new BullQueue(fullQueueName, {
|
||||
connection: { ...this.redisConnection, maxRetriesPerRequest: 1, enableOfflineQueue: false },
|
||||
});
|
||||
try {
|
||||
totalRemoved += await removeScheduledJobsFromBullQueue(tempQueue);
|
||||
} finally {
|
||||
await tempQueue.close().catch(error => {
|
||||
this.logger.warn('Error closing temporary reconciliation queue', {
|
||||
queueName: fullQueueName,
|
||||
error,
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.info('Reconciled disabled scheduled jobs for service queues', {
|
||||
service: this.serviceName || 'default',
|
||||
queueCount: seenFullNames.size,
|
||||
removedCount: totalRemoved,
|
||||
});
|
||||
|
||||
return totalRemoved;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for all queues to be ready
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -6,6 +6,53 @@ import type { QueueManager } from './queue-manager';
|
|||
import type { ExtendedJobOptions, JobData, JobOptions, QueueStats, RedisConfig } from './types';
|
||||
import { getRedisConnection } from './utils';
|
||||
|
||||
export type SchedulableBullQueue = Pick<
|
||||
BullQueue,
|
||||
'getRepeatableJobs' | 'removeRepeatableByKey' | 'getJobs'
|
||||
> &
|
||||
Partial<Pick<BullQueue, 'getJobSchedulers' | 'removeJobScheduler'>>;
|
||||
|
||||
/**
|
||||
* Remove all persisted repeatable/scheduled jobs and any pending repeat-spawned
|
||||
* job instances from a BullMQ queue while preserving manual (non-repeating) jobs.
|
||||
*/
|
||||
export async function removeScheduledJobsFromBullQueue(
|
||||
bullQueue: SchedulableBullQueue
|
||||
): Promise<number> {
|
||||
const removedKeys = new Set<string>();
|
||||
|
||||
const repeatableJobs = await bullQueue.getRepeatableJobs();
|
||||
for (const job of repeatableJobs) {
|
||||
if (job.key) {
|
||||
await bullQueue.removeRepeatableByKey(job.key);
|
||||
removedKeys.add(job.key);
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
typeof bullQueue.getJobSchedulers === 'function' &&
|
||||
typeof bullQueue.removeJobScheduler === 'function'
|
||||
) {
|
||||
const schedulers = await bullQueue.getJobSchedulers();
|
||||
for (const scheduler of schedulers) {
|
||||
if (scheduler.key && !removedKeys.has(scheduler.key)) {
|
||||
await bullQueue.removeJobScheduler(scheduler.key);
|
||||
removedKeys.add(scheduler.key);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const pendingJobs = await bullQueue.getJobs(['waiting', 'delayed', 'prioritized']);
|
||||
for (const job of pendingJobs) {
|
||||
const repeatKey = job?.repeatJobKey ?? job?.opts?.repeatJobKey;
|
||||
if (repeatKey) {
|
||||
await job.remove();
|
||||
}
|
||||
}
|
||||
|
||||
return removedKeys.size;
|
||||
}
|
||||
|
||||
export interface QueueWorkerConfig {
|
||||
workers?: number;
|
||||
concurrency?: number;
|
||||
|
|
@ -167,6 +214,19 @@ export class Queue {
|
|||
return await this.bullQueue.add(name, data, scheduledOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all persisted repeatable/scheduled jobs and any pending repeat-spawned
|
||||
* occurrences from this queue while preserving manual jobs.
|
||||
*/
|
||||
async removeAllScheduledJobs(): Promise<number> {
|
||||
const removedCount = await removeScheduledJobsFromBullQueue(this.bullQueue);
|
||||
this.logger.info('Removed scheduled jobs from queue', {
|
||||
queueName: this.queueName,
|
||||
removedCount,
|
||||
});
|
||||
return removedCount;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get queue statistics
|
||||
*/
|
||||
|
|
|
|||
|
|
@ -72,6 +72,7 @@ export interface QueueManagerConfig {
|
|||
redis: RedisConfig;
|
||||
defaultQueueOptions?: QueueOptions;
|
||||
enableScheduledJobs?: boolean;
|
||||
delayWorkerStart?: boolean;
|
||||
serviceName?: string; // For service discovery and namespacing
|
||||
autoDiscoverHandlers?: boolean; // Auto-discover queue routes from handler registry
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import { Queue } from '../src/queue';
|
||||
import { Queue, removeScheduledJobsFromBullQueue } from '../src/queue';
|
||||
import { QueueManager } from '../src/queue-manager';
|
||||
import type { QueueWorkerConfig, RedisConfig } from '../src/types';
|
||||
|
||||
describe('Queue Class', () => {
|
||||
|
|
@ -122,4 +123,221 @@ describe('Queue Class', () => {
|
|||
expect(queue.getWorkerCount()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('scheduled job reconciliation', () => {
|
||||
it('removes repeatable jobs, job schedulers, and pending/prioritized repeat instances while preserving manual jobs', async () => {
|
||||
const removedRepeatKeys: string[] = [];
|
||||
const removedSchedulerKeys: string[] = [];
|
||||
const removedJobIds: string[] = [];
|
||||
let requestedStates: string[] = [];
|
||||
|
||||
const fakeBullQueue = {
|
||||
getRepeatableJobs: mock(async () => [
|
||||
{ key: '{data-ingestion_te}:crawlScheduler', name: 'crawlScheduler' },
|
||||
]),
|
||||
removeRepeatableByKey: mock(async (key: string) => {
|
||||
removedRepeatKeys.push(key);
|
||||
return true;
|
||||
}),
|
||||
getJobSchedulers: mock(async () => [
|
||||
{ key: '{data-ingestion_te}:crawlScheduler', name: 'crawlScheduler' },
|
||||
{ key: '{data-ingestion_te}:dataScheduler', name: 'dataScheduler' },
|
||||
]),
|
||||
removeJobScheduler: mock(async (key: string) => {
|
||||
removedSchedulerKeys.push(key);
|
||||
return true;
|
||||
}),
|
||||
getJobs: mock(async (states: string[]) => {
|
||||
requestedStates = states;
|
||||
return [
|
||||
{
|
||||
id: 'repeat-job-1',
|
||||
repeatJobKey: '{data-ingestion_te}:crawlScheduler',
|
||||
remove: mock(async () => {
|
||||
removedJobIds.push('repeat-job-1');
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: 'prioritized-repeat-job-1',
|
||||
opts: { priority: 5, repeatJobKey: '{data-ingestion_te}:crawlScheduler' },
|
||||
remove: mock(async () => {
|
||||
removedJobIds.push('prioritized-repeat-job-1');
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: 'manual-eod-job-1',
|
||||
opts: {},
|
||||
remove: mock(async () => {
|
||||
removedJobIds.push('manual-eod-job-1');
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: 'prioritized-manual-job-1',
|
||||
opts: { priority: 5 },
|
||||
remove: mock(async () => {
|
||||
removedJobIds.push('prioritized-manual-job-1');
|
||||
}),
|
||||
},
|
||||
];
|
||||
}),
|
||||
};
|
||||
|
||||
const removedCount = await removeScheduledJobsFromBullQueue(fakeBullQueue as any);
|
||||
|
||||
expect(requestedStates).toEqual(['waiting', 'delayed', 'prioritized']);
|
||||
expect(removedCount).toBe(2);
|
||||
expect(removedRepeatKeys).toEqual(['{data-ingestion_te}:crawlScheduler']);
|
||||
expect(removedSchedulerKeys).toEqual(['{data-ingestion_te}:dataScheduler']);
|
||||
expect(removedJobIds).toEqual(['repeat-job-1', 'prioritized-repeat-job-1']);
|
||||
});
|
||||
|
||||
it('keeps owned queues workerless during initialization when delayWorkerStart is enabled until startAllWorkers is called', async () => {
|
||||
const mockLogger = {
|
||||
info: mock(() => {}),
|
||||
error: mock(() => {}),
|
||||
warn: mock(() => {}),
|
||||
debug: mock(() => {}),
|
||||
trace: mock(() => {}),
|
||||
};
|
||||
|
||||
const redisQuit = mock(async () => 'OK');
|
||||
const redisDisconnect = mock(() => {});
|
||||
const createRedis = mock(() => ({ quit: redisQuit, disconnect: redisDisconnect }) as any);
|
||||
|
||||
const createdQueues: Array<{
|
||||
name: string;
|
||||
workerConfig: QueueWorkerConfig;
|
||||
startWorkersManually: ReturnType<typeof mock>;
|
||||
close: ReturnType<typeof mock>;
|
||||
}> = [];
|
||||
|
||||
const createQueue = mock(
|
||||
(
|
||||
name: string,
|
||||
_redisConfig: RedisConfig,
|
||||
_defaultJobOptions: unknown,
|
||||
workerConfig: QueueWorkerConfig
|
||||
) => {
|
||||
let workerCount = workerConfig.startWorker ? (workerConfig.workers ?? 0) : 0;
|
||||
const startWorkersManually = mock((workers: number) => {
|
||||
workerCount = workers;
|
||||
});
|
||||
const close = mock(async () => {
|
||||
workerCount = 0;
|
||||
});
|
||||
const record = { name, workerConfig, startWorkersManually, close };
|
||||
createdQueues.push(record);
|
||||
return {
|
||||
getName: () => name,
|
||||
getWorkerCount: () => workerCount,
|
||||
startWorkersManually,
|
||||
close,
|
||||
} as unknown as Queue;
|
||||
}
|
||||
);
|
||||
|
||||
const manager = new QueueManager(
|
||||
{
|
||||
serviceName: 'test-ingestion',
|
||||
redis: { ...mockRedisConfig, maxRetriesPerRequest: 1 },
|
||||
delayWorkerStart: true,
|
||||
defaultQueueOptions: { workers: 1, concurrency: 2 },
|
||||
},
|
||||
undefined,
|
||||
mockLogger,
|
||||
{ createRedis, createQueue }
|
||||
);
|
||||
|
||||
try {
|
||||
const teQueue = manager.getQueue('te');
|
||||
expect(createRedis).toHaveBeenCalledTimes(1);
|
||||
expect(createQueue).toHaveBeenCalledTimes(1);
|
||||
expect(teQueue.getName()).toBe('{test-ingestion_te}');
|
||||
expect(createdQueues[0]?.workerConfig.startWorker).toBe(false);
|
||||
expect(createdQueues[0]?.workerConfig.workers).toBe(1);
|
||||
expect(createdQueues[0]?.workerConfig.concurrency).toBe(2);
|
||||
// Queue must stay workerless while handlers initialize and schedules reconcile
|
||||
expect(teQueue.getWorkerCount()).toBe(0);
|
||||
|
||||
manager.startAllWorkers();
|
||||
expect(createdQueues[0]?.startWorkersManually).toHaveBeenCalledTimes(1);
|
||||
expect(createdQueues[0]?.startWorkersManually).toHaveBeenCalledWith(1, 2);
|
||||
expect(teQueue.getWorkerCount()).toBe(1);
|
||||
} finally {
|
||||
await manager.shutdown();
|
||||
}
|
||||
|
||||
expect(createdQueues[0]?.close).toHaveBeenCalledTimes(1);
|
||||
expect(redisQuit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('starts workers immediately with explicit worker settings when delayWorkerStart is false', async () => {
|
||||
const mockLogger = {
|
||||
info: mock(() => {}),
|
||||
error: mock(() => {}),
|
||||
warn: mock(() => {}),
|
||||
debug: mock(() => {}),
|
||||
trace: mock(() => {}),
|
||||
};
|
||||
|
||||
const redisQuit = mock(async () => 'OK');
|
||||
const redisDisconnect = mock(() => {});
|
||||
const createRedis = mock(() => ({ quit: redisQuit, disconnect: redisDisconnect }) as any);
|
||||
|
||||
const createdQueues: Array<{
|
||||
name: string;
|
||||
workerConfig: QueueWorkerConfig;
|
||||
close: ReturnType<typeof mock>;
|
||||
}> = [];
|
||||
|
||||
const createQueue = mock(
|
||||
(
|
||||
name: string,
|
||||
_redisConfig: RedisConfig,
|
||||
_defaultJobOptions: unknown,
|
||||
workerConfig: QueueWorkerConfig
|
||||
) => {
|
||||
const workerCount = workerConfig.startWorker ? (workerConfig.workers ?? 0) : 0;
|
||||
const close = mock(async () => {});
|
||||
createdQueues.push({ name, workerConfig, close });
|
||||
return {
|
||||
getName: () => name,
|
||||
getWorkerCount: () => workerCount,
|
||||
close,
|
||||
} as unknown as Queue;
|
||||
}
|
||||
);
|
||||
|
||||
const manager = new QueueManager(
|
||||
{
|
||||
serviceName: 'orchestrator',
|
||||
redis: { ...mockRedisConfig, maxRetriesPerRequest: 1 },
|
||||
delayWorkerStart: false,
|
||||
defaultQueueOptions: { workers: 1, concurrency: 1 },
|
||||
},
|
||||
undefined,
|
||||
mockLogger,
|
||||
{ createRedis, createQueue }
|
||||
);
|
||||
|
||||
try {
|
||||
const orchestratorQueue = manager.getQueue('orchestrator', {
|
||||
workers: 1,
|
||||
concurrency: 4,
|
||||
});
|
||||
expect(createRedis).toHaveBeenCalledTimes(1);
|
||||
expect(createQueue).toHaveBeenCalledTimes(1);
|
||||
expect(orchestratorQueue.getName()).toBe('{orchestrator_orchestrator}');
|
||||
expect(createdQueues[0]?.workerConfig.startWorker).toBe(true);
|
||||
expect(createdQueues[0]?.workerConfig.workers).toBe(1);
|
||||
expect(createdQueues[0]?.workerConfig.concurrency).toBe(4);
|
||||
expect(orchestratorQueue.getWorkerCount()).toBe(1);
|
||||
} finally {
|
||||
await manager.shutdown();
|
||||
}
|
||||
|
||||
expect(createdQueues[0]?.close).toHaveBeenCalledTimes(1);
|
||||
expect(redisQuit).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,5 +1,7 @@
|
|||
import { Readable } from 'node:stream';
|
||||
import type {
|
||||
AggregateOptions,
|
||||
AggregationCursor,
|
||||
BulkWriteOptions,
|
||||
CountDocumentsOptions,
|
||||
CreateCollectionOptions,
|
||||
|
|
@ -22,6 +24,29 @@ import type {
|
|||
PoolMetrics,
|
||||
} from './types';
|
||||
|
||||
const READ_ONLY_CURSOR_FLUENT_MODIFIERS = [
|
||||
'filter',
|
||||
'hint',
|
||||
'min',
|
||||
'max',
|
||||
'returnKey',
|
||||
'showRecordId',
|
||||
'addQueryModifier',
|
||||
'comment',
|
||||
'maxAwaitTimeMS',
|
||||
'maxTimeMS',
|
||||
'project',
|
||||
'sort',
|
||||
'allowDiskUse',
|
||||
'collation',
|
||||
'limit',
|
||||
'skip',
|
||||
'batchSize',
|
||||
'withReadPreference',
|
||||
'withReadConcern',
|
||||
'addCursorFlag',
|
||||
] as const;
|
||||
|
||||
const READ_ONLY_COLLECTION_METHODS = new Set<string | symbol>([
|
||||
'find',
|
||||
'findOne',
|
||||
|
|
@ -185,21 +210,604 @@ export class MongoDBClient {
|
|||
return this.client.db(databaseName || this.defaultDatabase);
|
||||
}
|
||||
|
||||
private createGuardedCursorStream(
|
||||
cursor: {
|
||||
next: () => Promise<unknown>;
|
||||
close?: () => Promise<unknown>;
|
||||
},
|
||||
options?: { transform?: (doc: never) => unknown },
|
||||
beforeRead?: () => void
|
||||
): Readable {
|
||||
beforeRead?.();
|
||||
const transform = options?.transform;
|
||||
let closePromise: Promise<unknown> | null = null;
|
||||
const closeCursor = (): Promise<unknown> => {
|
||||
if (!closePromise) {
|
||||
closePromise = typeof cursor.close === 'function' ? cursor.close() : Promise.resolve();
|
||||
}
|
||||
return closePromise;
|
||||
};
|
||||
let readInProgress = false;
|
||||
|
||||
return new Readable({
|
||||
objectMode: true,
|
||||
autoDestroy: false,
|
||||
highWaterMark: 1,
|
||||
read() {
|
||||
if (readInProgress) {
|
||||
return;
|
||||
}
|
||||
readInProgress = true;
|
||||
const readNext = (): void => {
|
||||
try {
|
||||
beforeRead?.();
|
||||
} catch (err) {
|
||||
readInProgress = false;
|
||||
this.destroy(err instanceof Error ? err : new Error(String(err)));
|
||||
return;
|
||||
}
|
||||
|
||||
cursor.next().then(
|
||||
doc => {
|
||||
if (doc == null) {
|
||||
readInProgress = false;
|
||||
closeCursor().then(
|
||||
() => {
|
||||
if (!this.destroyed) {
|
||||
this.push(null);
|
||||
}
|
||||
},
|
||||
closeError => {
|
||||
this.destroy(
|
||||
closeError instanceof Error ? closeError : new Error(String(closeError))
|
||||
);
|
||||
}
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (this.destroyed) {
|
||||
readInProgress = false;
|
||||
closeCursor().catch(() => {});
|
||||
return;
|
||||
}
|
||||
let output: unknown = doc;
|
||||
if (transform) {
|
||||
try {
|
||||
output = transform(doc as never);
|
||||
} catch (err) {
|
||||
readInProgress = false;
|
||||
this.destroy(err instanceof Error ? err : new Error(String(err)));
|
||||
return;
|
||||
}
|
||||
if (output == null) {
|
||||
readNext();
|
||||
return;
|
||||
}
|
||||
}
|
||||
if (this.push(output)) {
|
||||
readNext();
|
||||
} else {
|
||||
readInProgress = false;
|
||||
}
|
||||
},
|
||||
err => {
|
||||
readInProgress = false;
|
||||
this.destroy(err instanceof Error ? err : new Error(String(err)));
|
||||
}
|
||||
);
|
||||
};
|
||||
readNext();
|
||||
},
|
||||
destroy(error, callback) {
|
||||
closeCursor().then(
|
||||
() => callback(error),
|
||||
closeError =>
|
||||
callback(closeError instanceof Error ? closeError : new Error(String(closeError)))
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
private createTrackedCursorEventMethods(
|
||||
cursor: Record<PropertyKey, unknown>,
|
||||
wrapped: Record<PropertyKey, unknown>
|
||||
): Record<string, unknown> {
|
||||
type CursorListener = (...args: unknown[]) => void;
|
||||
interface TrackedListener {
|
||||
original: CursorListener;
|
||||
bound: CursorListener;
|
||||
once: boolean;
|
||||
}
|
||||
const trackedListeners = new Map<string | symbol, TrackedListener[]>();
|
||||
|
||||
const invokeCursorEventMethod = (method: string, ...args: unknown[]): unknown => {
|
||||
const fn = cursor[method];
|
||||
return typeof fn === 'function' ? fn.apply(cursor, args) : undefined;
|
||||
};
|
||||
|
||||
const detachFromCursor = (event: string | symbol, bound: CursorListener): void => {
|
||||
if (typeof cursor.removeListener === 'function') {
|
||||
invokeCursorEventMethod('removeListener', event, bound);
|
||||
} else if (typeof cursor.off === 'function') {
|
||||
invokeCursorEventMethod('off', event, bound);
|
||||
}
|
||||
};
|
||||
|
||||
const removeTrackedEntry = (event: string | symbol, entry: TrackedListener): void => {
|
||||
const entries = trackedListeners.get(event);
|
||||
if (!entries) {
|
||||
return;
|
||||
}
|
||||
const index = entries.indexOf(entry);
|
||||
if (index !== -1) {
|
||||
entries.splice(index, 1);
|
||||
}
|
||||
if (entries.length === 0) {
|
||||
trackedListeners.delete(event);
|
||||
}
|
||||
};
|
||||
|
||||
const registerTrackedListener = (
|
||||
event: string | symbol,
|
||||
listener: CursorListener,
|
||||
options: { once: boolean; prepend: boolean }
|
||||
) => {
|
||||
const entry: TrackedListener = {
|
||||
original: listener,
|
||||
once: options.once,
|
||||
bound: (...args: unknown[]) => {
|
||||
if (entry.once) {
|
||||
removeTrackedEntry(event, entry);
|
||||
}
|
||||
listener.apply(wrapped, args);
|
||||
},
|
||||
};
|
||||
|
||||
const entries = trackedListeners.get(event) ?? [];
|
||||
if (options.prepend) {
|
||||
entries.unshift(entry);
|
||||
} else {
|
||||
entries.push(entry);
|
||||
}
|
||||
trackedListeners.set(event, entries);
|
||||
|
||||
if (options.prepend) {
|
||||
if (options.once) {
|
||||
invokeCursorEventMethod('prependOnceListener', event, entry.bound);
|
||||
} else {
|
||||
invokeCursorEventMethod('prependListener', event, entry.bound);
|
||||
}
|
||||
} else if (options.once) {
|
||||
invokeCursorEventMethod('once', event, entry.bound);
|
||||
} else {
|
||||
invokeCursorEventMethod('on', event, entry.bound);
|
||||
}
|
||||
|
||||
return wrapped;
|
||||
};
|
||||
|
||||
const unregisterTrackedListener = (event: string | symbol, listener: CursorListener) => {
|
||||
const entries = trackedListeners.get(event);
|
||||
if (!entries) {
|
||||
return wrapped;
|
||||
}
|
||||
let index = -1;
|
||||
for (let i = entries.length - 1; i >= 0; i--) {
|
||||
if (entries[i]?.original === listener) {
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (index !== -1) {
|
||||
const [removed] = entries.splice(index, 1);
|
||||
if (entries.length === 0) {
|
||||
trackedListeners.delete(event);
|
||||
}
|
||||
if (removed) {
|
||||
detachFromCursor(event, removed.bound);
|
||||
}
|
||||
}
|
||||
return wrapped;
|
||||
};
|
||||
|
||||
return {
|
||||
on: (event: string | symbol, listener: CursorListener) =>
|
||||
registerTrackedListener(event, listener, { once: false, prepend: false }),
|
||||
once: (event: string | symbol, listener: CursorListener) =>
|
||||
registerTrackedListener(event, listener, { once: true, prepend: false }),
|
||||
off: (event: string | symbol, listener: CursorListener) =>
|
||||
unregisterTrackedListener(event, listener),
|
||||
addListener: (event: string | symbol, listener: CursorListener) =>
|
||||
registerTrackedListener(event, listener, { once: false, prepend: false }),
|
||||
removeListener: (event: string | symbol, listener: CursorListener) =>
|
||||
unregisterTrackedListener(event, listener),
|
||||
removeAllListeners: (event?: string | symbol) => {
|
||||
if (event !== undefined) {
|
||||
const entries = trackedListeners.get(event);
|
||||
if (entries) {
|
||||
for (const entry of entries) {
|
||||
detachFromCursor(event, entry.bound);
|
||||
}
|
||||
trackedListeners.delete(event);
|
||||
}
|
||||
} else {
|
||||
for (const [ev, entries] of trackedListeners) {
|
||||
for (const entry of entries) {
|
||||
detachFromCursor(ev, entry.bound);
|
||||
}
|
||||
}
|
||||
trackedListeners.clear();
|
||||
}
|
||||
return wrapped;
|
||||
},
|
||||
prependListener: (event: string | symbol, listener: CursorListener) =>
|
||||
registerTrackedListener(event, listener, { once: false, prepend: true }),
|
||||
prependOnceListener: (event: string | symbol, listener: CursorListener) =>
|
||||
registerTrackedListener(event, listener, { once: true, prepend: true }),
|
||||
setMaxListeners: (n: number) => {
|
||||
invokeCursorEventMethod('setMaxListeners', n);
|
||||
return wrapped;
|
||||
},
|
||||
getMaxListeners: () =>
|
||||
typeof cursor.getMaxListeners === 'function'
|
||||
? (invokeCursorEventMethod('getMaxListeners') as number)
|
||||
: 10,
|
||||
listeners: (event: string | symbol) =>
|
||||
(trackedListeners.get(event) ?? []).map(entry => entry.original),
|
||||
rawListeners: (event: string | symbol) =>
|
||||
(trackedListeners.get(event) ?? []).map(entry => entry.original),
|
||||
listenerCount: (event: string | symbol) => trackedListeners.get(event)?.length ?? 0,
|
||||
eventNames: () => Array.from(trackedListeners.keys()),
|
||||
};
|
||||
}
|
||||
|
||||
private wrapReadOnlyCursor<TCursor extends object>(cursor: TCursor): TCursor {
|
||||
const rawCursor = cursor as Record<PropertyKey, unknown>;
|
||||
|
||||
const delegate = (method: string) => (...args: unknown[]) => {
|
||||
const fn = rawCursor[method];
|
||||
if (typeof fn !== 'function') {
|
||||
throw new TypeError(`Cursor does not implement "${method}"`);
|
||||
}
|
||||
return fn.apply(cursor, args);
|
||||
};
|
||||
|
||||
const wrapped: Record<PropertyKey, unknown> = {
|
||||
get id() {
|
||||
return rawCursor.id;
|
||||
},
|
||||
get namespace() {
|
||||
return rawCursor.namespace;
|
||||
},
|
||||
get readPreference() {
|
||||
return rawCursor.readPreference;
|
||||
},
|
||||
get readConcern() {
|
||||
return rawCursor.readConcern;
|
||||
},
|
||||
get closed() {
|
||||
return rawCursor.closed;
|
||||
},
|
||||
get killed() {
|
||||
return rawCursor.killed;
|
||||
},
|
||||
get loadBalanced() {
|
||||
return rawCursor.loadBalanced;
|
||||
},
|
||||
toArray: delegate('toArray'),
|
||||
next: delegate('next'),
|
||||
tryNext: delegate('tryNext'),
|
||||
hasNext: delegate('hasNext'),
|
||||
forEach: (iterator: (doc: unknown) => boolean | void) => {
|
||||
const fn = rawCursor.forEach;
|
||||
if (typeof fn !== 'function') {
|
||||
throw new TypeError('Cursor does not implement "forEach"');
|
||||
}
|
||||
if (typeof iterator !== 'function') {
|
||||
return fn.call(cursor, iterator);
|
||||
}
|
||||
return fn.call(cursor, (doc: unknown) => iterator.call(wrapped, doc));
|
||||
},
|
||||
count: delegate('count'),
|
||||
explain: delegate('explain'),
|
||||
close: delegate('close'),
|
||||
rewind: delegate('rewind'),
|
||||
bufferedCount: delegate('bufferedCount'),
|
||||
readBufferedDocuments: delegate('readBufferedDocuments'),
|
||||
stream: (options?: { transform?: (doc: never) => unknown }) =>
|
||||
this.createGuardedCursorStream(
|
||||
rawCursor as unknown as {
|
||||
next: () => Promise<unknown>;
|
||||
close?: () => Promise<unknown>;
|
||||
},
|
||||
options
|
||||
),
|
||||
[Symbol.asyncIterator]: () => {
|
||||
const iterator = rawCursor[Symbol.asyncIterator];
|
||||
if (typeof iterator !== 'function') {
|
||||
throw new TypeError('Cursor is not async iterable');
|
||||
}
|
||||
return iterator.call(cursor);
|
||||
},
|
||||
[Symbol.asyncDispose]: () => {
|
||||
const dispose = rawCursor[Symbol.asyncDispose];
|
||||
if (typeof dispose === 'function') {
|
||||
return dispose.call(cursor);
|
||||
}
|
||||
const close = rawCursor.close;
|
||||
return typeof close === 'function' ? close.call(cursor) : Promise.resolve();
|
||||
},
|
||||
map: (transform: (doc: unknown) => unknown) => {
|
||||
const fn = rawCursor.map;
|
||||
if (typeof fn !== 'function') {
|
||||
throw new TypeError('Cursor does not implement "map"');
|
||||
}
|
||||
let receiver: unknown;
|
||||
const guardedTransform =
|
||||
typeof transform === 'function'
|
||||
? (doc: unknown) => transform.call(receiver, doc)
|
||||
: transform;
|
||||
const mapped = fn.call(cursor, guardedTransform);
|
||||
const result =
|
||||
mapped === cursor
|
||||
? wrapped
|
||||
: mapped && typeof mapped === 'object'
|
||||
? this.wrapReadOnlyCursor(mapped as object)
|
||||
: mapped;
|
||||
receiver = result;
|
||||
return result;
|
||||
},
|
||||
clone: () => {
|
||||
const fn = rawCursor.clone;
|
||||
if (typeof fn !== 'function') {
|
||||
throw new TypeError('Cursor does not implement "clone"');
|
||||
}
|
||||
const cloned = fn.call(cursor);
|
||||
return cloned && typeof cloned === 'object'
|
||||
? this.wrapReadOnlyCursor(cloned as object)
|
||||
: cloned;
|
||||
},
|
||||
};
|
||||
|
||||
for (const modifier of READ_ONLY_CURSOR_FLUENT_MODIFIERS) {
|
||||
if (typeof rawCursor[modifier] === 'function') {
|
||||
wrapped[modifier] = (...args: unknown[]) => {
|
||||
const fn = rawCursor[modifier] as (...modifierArgs: unknown[]) => unknown;
|
||||
const result = fn.apply(cursor, args);
|
||||
if (result === cursor) {
|
||||
return wrapped;
|
||||
}
|
||||
if (result && typeof result === 'object') {
|
||||
return this.wrapReadOnlyCursor(result as object);
|
||||
}
|
||||
return result;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
Object.assign(wrapped, this.createTrackedCursorEventMethods(rawCursor, wrapped));
|
||||
|
||||
return wrapped as unknown as TCursor;
|
||||
}
|
||||
|
||||
private wrapReadOnlyAggregationCursor<T extends Document>(
|
||||
cursor: AggregationCursor<T>
|
||||
): AggregationCursor<T> {
|
||||
const assertCursorPipelineSafe = (): void => {
|
||||
if (Array.isArray(cursor.pipeline)) {
|
||||
this.assertReadOnlyPipeline(cursor.pipeline);
|
||||
}
|
||||
};
|
||||
|
||||
const wrapped: Record<PropertyKey, unknown> = {
|
||||
get id() {
|
||||
return cursor.id;
|
||||
},
|
||||
get namespace() {
|
||||
return cursor.namespace;
|
||||
},
|
||||
get readPreference() {
|
||||
return cursor.readPreference;
|
||||
},
|
||||
get readConcern() {
|
||||
return cursor.readConcern;
|
||||
},
|
||||
get closed() {
|
||||
return cursor.closed;
|
||||
},
|
||||
get killed() {
|
||||
return cursor.killed;
|
||||
},
|
||||
get loadBalanced() {
|
||||
return cursor.loadBalanced;
|
||||
},
|
||||
get pipeline() {
|
||||
return Object.freeze(Array.isArray(cursor.pipeline) ? [...cursor.pipeline] : []);
|
||||
},
|
||||
// Read / iteration operations
|
||||
toArray: () => {
|
||||
assertCursorPipelineSafe();
|
||||
return cursor.toArray();
|
||||
},
|
||||
next: () => {
|
||||
assertCursorPipelineSafe();
|
||||
return cursor.next();
|
||||
},
|
||||
tryNext: () => {
|
||||
assertCursorPipelineSafe();
|
||||
return cursor.tryNext();
|
||||
},
|
||||
hasNext: () => {
|
||||
assertCursorPipelineSafe();
|
||||
return cursor.hasNext();
|
||||
},
|
||||
forEach: (iterator: (doc: T) => boolean | void) => {
|
||||
assertCursorPipelineSafe();
|
||||
if (typeof iterator !== 'function') {
|
||||
return cursor.forEach(iterator);
|
||||
}
|
||||
return cursor.forEach(doc => iterator.call(wrapped, doc));
|
||||
},
|
||||
stream: (options?: Parameters<AggregationCursor<T>['stream']>[0]) =>
|
||||
this.createGuardedCursorStream(
|
||||
cursor as unknown as {
|
||||
next: () => Promise<unknown>;
|
||||
close?: () => Promise<unknown>;
|
||||
},
|
||||
options as { transform?: (doc: never) => unknown } | undefined,
|
||||
assertCursorPipelineSafe
|
||||
) as ReturnType<AggregationCursor<T>['stream']>,
|
||||
explain: (...args: Parameters<AggregationCursor<T>['explain']>) => {
|
||||
assertCursorPipelineSafe();
|
||||
return cursor.explain(...args);
|
||||
},
|
||||
close: (...args: Parameters<AggregationCursor<T>['close']>) => cursor.close(...args),
|
||||
rewind: () => cursor.rewind(),
|
||||
bufferedCount: () => cursor.bufferedCount(),
|
||||
readBufferedDocuments: (count?: number) => cursor.readBufferedDocuments(count),
|
||||
[Symbol.asyncIterator]: () => {
|
||||
assertCursorPipelineSafe();
|
||||
return cursor[Symbol.asyncIterator]();
|
||||
},
|
||||
[Symbol.asyncDispose]: () => {
|
||||
const disposable = cursor as unknown as Partial<Record<symbol, () => Promise<void>>>;
|
||||
const dispose = disposable[Symbol.asyncDispose];
|
||||
return typeof dispose === 'function' ? dispose.call(cursor) : cursor.close();
|
||||
},
|
||||
// Fluent stage builders (read-only stages validated and wrapped)
|
||||
out: () => {
|
||||
throw new Error(
|
||||
'MongoDB client is configured in read-only mode; aggregation cursor operation "out" is forbidden'
|
||||
);
|
||||
},
|
||||
addStage: (stage: Document) => {
|
||||
this.assertReadOnlyPipeline([stage]);
|
||||
cursor.addStage(stage);
|
||||
return wrapped;
|
||||
},
|
||||
lookup: ($lookup: Document) => {
|
||||
this.assertReadOnlyPipeline([{ $lookup }]);
|
||||
cursor.lookup($lookup);
|
||||
return wrapped;
|
||||
},
|
||||
match: ($match: Document) => {
|
||||
cursor.match($match);
|
||||
return wrapped;
|
||||
},
|
||||
project: ($project: Document) => {
|
||||
cursor.project($project);
|
||||
return wrapped;
|
||||
},
|
||||
group: ($group: Document) => {
|
||||
cursor.group($group);
|
||||
return wrapped;
|
||||
},
|
||||
sort: ($sort: Parameters<AggregationCursor<T>['sort']>[0]) => {
|
||||
cursor.sort($sort);
|
||||
return wrapped;
|
||||
},
|
||||
limit: ($limit: number) => {
|
||||
cursor.limit($limit);
|
||||
return wrapped;
|
||||
},
|
||||
skip: ($skip: number) => {
|
||||
cursor.skip($skip);
|
||||
return wrapped;
|
||||
},
|
||||
unwind: ($unwind: Document | string) => {
|
||||
cursor.unwind($unwind);
|
||||
return wrapped;
|
||||
},
|
||||
redact: ($redact: Document) => {
|
||||
cursor.redact($redact);
|
||||
return wrapped;
|
||||
},
|
||||
geoNear: ($geoNear: Document) => {
|
||||
cursor.geoNear($geoNear);
|
||||
return wrapped;
|
||||
},
|
||||
// Fluent cursor modifiers
|
||||
batchSize: (value: number) => {
|
||||
cursor.batchSize(value);
|
||||
return wrapped;
|
||||
},
|
||||
maxTimeMS: (value: number) => {
|
||||
cursor.maxTimeMS(value);
|
||||
return wrapped;
|
||||
},
|
||||
withReadPreference: (value: Parameters<AggregationCursor<T>['withReadPreference']>[0]) => {
|
||||
cursor.withReadPreference(value);
|
||||
return wrapped;
|
||||
},
|
||||
withReadConcern: (value: Parameters<AggregationCursor<T>['withReadConcern']>[0]) => {
|
||||
cursor.withReadConcern(value);
|
||||
return wrapped;
|
||||
},
|
||||
addCursorFlag: (
|
||||
flag: Parameters<AggregationCursor<T>['addCursorFlag']>[0],
|
||||
value: boolean
|
||||
) => {
|
||||
cursor.addCursorFlag(flag, value);
|
||||
return wrapped;
|
||||
},
|
||||
map: <TMapped>(transform: (doc: T) => TMapped) => {
|
||||
let receiver: unknown;
|
||||
const guardedTransform =
|
||||
typeof transform === 'function'
|
||||
? (doc: T) => transform.call(receiver, doc)
|
||||
: transform;
|
||||
const mapped = cursor.map(guardedTransform);
|
||||
const result =
|
||||
mapped === (cursor as unknown)
|
||||
? wrapped
|
||||
: this.wrapReadOnlyAggregationCursor(mapped as unknown as AggregationCursor<Document>);
|
||||
receiver = result;
|
||||
return result;
|
||||
},
|
||||
clone: () => this.wrapReadOnlyAggregationCursor(cursor.clone()),
|
||||
};
|
||||
|
||||
Object.assign(
|
||||
wrapped,
|
||||
this.createTrackedCursorEventMethods(cursor as unknown as Record<PropertyKey, unknown>, wrapped)
|
||||
);
|
||||
|
||||
return wrapped as unknown as AggregationCursor<T>;
|
||||
}
|
||||
|
||||
private wrapReadOnlyCollection<T extends Document>(collection: Collection<T>): Collection<T> {
|
||||
return new Proxy(collection, {
|
||||
get: (target, prop, receiver) => {
|
||||
return new Proxy({} as Collection<T>, {
|
||||
get: (_target, prop) => {
|
||||
if (typeof prop === 'symbol' || READ_ONLY_COLLECTION_PROPS.has(prop)) {
|
||||
return Reflect.get(target, prop, receiver);
|
||||
return Reflect.get(collection, prop, collection);
|
||||
}
|
||||
if (prop === 'aggregate') {
|
||||
return (pipeline: Document[] = [], options?: AggregateOptions) => {
|
||||
this.assertReadOnlyPipeline(pipeline);
|
||||
return target.aggregate(pipeline, options);
|
||||
return <TDoc extends Document = Document>(
|
||||
pipeline: Document[] = [],
|
||||
options?: AggregateOptions
|
||||
) => {
|
||||
const safePipeline = [...pipeline];
|
||||
this.assertReadOnlyPipeline(safePipeline);
|
||||
return this.wrapReadOnlyAggregationCursor(
|
||||
collection.aggregate<TDoc>(safePipeline, options)
|
||||
);
|
||||
};
|
||||
}
|
||||
if (prop === 'find' || prop === 'listIndexes') {
|
||||
const fn: unknown = Reflect.get(collection, prop, collection);
|
||||
if (typeof fn === 'function') {
|
||||
return (...args: unknown[]) => {
|
||||
const cursor = (fn as (...methodArgs: unknown[]) => unknown).apply(collection, args);
|
||||
return cursor && typeof cursor === 'object'
|
||||
? this.wrapReadOnlyCursor(cursor as object)
|
||||
: cursor;
|
||||
};
|
||||
}
|
||||
return fn;
|
||||
}
|
||||
if (READ_ONLY_COLLECTION_METHODS.has(prop)) {
|
||||
const fn = Reflect.get(target, prop, target);
|
||||
return typeof fn === 'function' ? fn.bind(target) : fn;
|
||||
const fn = Reflect.get(collection, prop, collection);
|
||||
return typeof fn === 'function' ? fn.bind(collection) : fn;
|
||||
}
|
||||
return () => {
|
||||
throw new Error(
|
||||
|
|
@ -211,18 +819,30 @@ export class MongoDBClient {
|
|||
}
|
||||
|
||||
private wrapReadOnlyDatabase(db: Db): Db {
|
||||
return new Proxy(db, {
|
||||
get: (target, prop, receiver) => {
|
||||
return new Proxy({} as Db, {
|
||||
get: (_target, prop) => {
|
||||
if (typeof prop === 'symbol' || READ_ONLY_DB_PROPS.has(prop)) {
|
||||
return Reflect.get(target, prop, receiver);
|
||||
return Reflect.get(db, prop, db);
|
||||
}
|
||||
if (prop === 'collection') {
|
||||
return <T extends Document = Document>(name: string) =>
|
||||
this.wrapReadOnlyCollection(target.collection<T>(name));
|
||||
this.wrapReadOnlyCollection(db.collection<T>(name));
|
||||
}
|
||||
if (prop === 'listCollections') {
|
||||
const fn: unknown = Reflect.get(db, prop, db);
|
||||
if (typeof fn === 'function') {
|
||||
return (...args: unknown[]) => {
|
||||
const cursor = (fn as (...methodArgs: unknown[]) => unknown).apply(db, args);
|
||||
return cursor && typeof cursor === 'object'
|
||||
? this.wrapReadOnlyCursor(cursor as object)
|
||||
: cursor;
|
||||
};
|
||||
}
|
||||
return fn;
|
||||
}
|
||||
if (READ_ONLY_DB_METHODS.has(prop)) {
|
||||
const fn = Reflect.get(target, prop, target);
|
||||
return typeof fn === 'function' ? fn.bind(target) : fn;
|
||||
const fn = Reflect.get(db, prop, db);
|
||||
return typeof fn === 'function' ? fn.bind(db) : fn;
|
||||
}
|
||||
return () => {
|
||||
throw new Error(
|
||||
|
|
|
|||
239
test/unit/environment-safety-edge-cases.test.ts
Normal file
239
test/unit/environment-safety-edge-cases.test.ts
Normal file
|
|
@ -0,0 +1,239 @@
|
|||
import { readFileSync } from 'fs';
|
||||
import path from 'path';
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { queueConfigSchema as coreQueueConfigSchema } from '../../libs/core/config/src/schemas';
|
||||
import { queueConfigSchema as diQueueConfigSchema } from '@stock-bot/di';
|
||||
import { setLoggerConfig } from '@stock-bot/logger';
|
||||
import { assertEnvironmentSafety, stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config';
|
||||
|
||||
// T-7 edge cases for the dev QA-Mongo guard and the scheduled-jobs default.
|
||||
// Pure config objects only: 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 READ_URI = 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock';
|
||||
const PIPELINE_ERROR = /MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/;
|
||||
const WRITE_ERROR = /cannot open a writable MongoDB connection to QA MongoDB/;
|
||||
|
||||
function makeConfig(o: {
|
||||
environment?: 'development' | 'qa' | 'test' | 'production';
|
||||
mongoEnabled?: boolean;
|
||||
mongoUri?: string;
|
||||
mongoReadUri?: string | null;
|
||||
mongoReadOnly?: boolean;
|
||||
mongoDatabase?: string;
|
||||
pgDatabase?: string;
|
||||
} = {}): StockAppConfig {
|
||||
const mongodb: Record<string, unknown> = {
|
||||
enabled: o.mongoEnabled ?? true,
|
||||
uri: o.mongoUri ?? DEV_MONGO_URI,
|
||||
readOnly: o.mongoReadOnly ?? false,
|
||||
database: o.mongoDatabase ?? 'stock_dev',
|
||||
};
|
||||
if (o.mongoReadUri !== null) {
|
||||
mongodb.readUri = o.mongoReadUri ?? READ_URI;
|
||||
}
|
||||
return stockAppSchema.parse({
|
||||
name: 'stock-bot',
|
||||
version: '1.0.0',
|
||||
environment: o.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: o.pgDatabase ?? '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: {},
|
||||
});
|
||||
}
|
||||
|
||||
describe('dev QA-Mongo guard: loopback :27017 host variants', () => {
|
||||
const qaVariants = [
|
||||
'mongodb://studio_stock_bot_read:secret@127.0.0.1:27017/stock',
|
||||
'mongodb://studio_stock_bot_read:secret@0.0.0.0:27017/stock',
|
||||
'mongodb://studio_stock_bot_read:secret@[::1]:27017/stock',
|
||||
'mongodb://studio_stock_bot_read:secret@LOCALHOST:27017/stock',
|
||||
// No explicit port: the driver defaults to 27017.
|
||||
'mongodb://studio_stock_bot_read:secret@localhost/stock',
|
||||
// No db path and no trailing slash.
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017',
|
||||
// Different db name on the same QA server is still the QA server.
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017/other',
|
||||
];
|
||||
|
||||
for (const uri of qaVariants) {
|
||||
test(`non-readOnly dataPipeline reading ${uri} throws with fix guidance`, () => {
|
||||
const cfg = makeConfig({ mongoReadUri: uri, mongoReadOnly: false });
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR);
|
||||
});
|
||||
|
||||
test(`readOnly dataPipeline reading ${uri} as the read user passes`, () => {
|
||||
const cfg = makeConfig({ mongoReadUri: uri, mongoReadOnly: true });
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test(`writable dataIngestion on ${uri} throws`, () => {
|
||||
const cfg = makeConfig({ mongoUri: uri, mongoReadUri: null, mongoDatabase: 'other' });
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).toThrow(WRITE_ERROR);
|
||||
});
|
||||
}
|
||||
|
||||
test('non-loopback host on :27017 is not treated as local QA Mongo', () => {
|
||||
const cfg = makeConfig({
|
||||
mongoUri: 'mongodb://writer:pw@10.0.0.51:27017/stock',
|
||||
mongoReadUri: 'mongodb://reader:pw@10.0.0.51:27017/stock',
|
||||
mongoReadOnly: false,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow();
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
describe('dev QA-Mongo guard: dataPipeline credential and target rules', () => {
|
||||
test('percent-encoded trading_admin username is still recognised and blocked', () => {
|
||||
const cfg = makeConfig({
|
||||
mongoReadUri: 'mongodb://trading%5Fadmin:pw@localhost:27017/stock',
|
||||
mongoReadOnly: true,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR);
|
||||
});
|
||||
|
||||
test('without readUri the pipeline falls back to uri, so trading_admin@27017 in uri throws', () => {
|
||||
const cfg = makeConfig({
|
||||
mongoUri: 'mongodb://trading_admin:pw@localhost:27017/stock',
|
||||
mongoReadUri: null,
|
||||
mongoReadOnly: true,
|
||||
mongoDatabase: 'stock',
|
||||
});
|
||||
expect(cfg.database.mongodb.readUri).toBeUndefined();
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR);
|
||||
});
|
||||
|
||||
test('without readUri, a non-readOnly pipeline on uri localhost:27017 throws', () => {
|
||||
const cfg = makeConfig({ mongoUri: READ_URI, mongoReadUri: null, mongoReadOnly: false });
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(PIPELINE_ERROR);
|
||||
});
|
||||
|
||||
test('readUri wins over uri: a dev :27018 readUri passes even when uri points at QA :27017', () => {
|
||||
const cfg = makeConfig({
|
||||
mongoUri: 'mongodb://trading_admin:pw@localhost:27017/stock',
|
||||
mongoReadUri: DEV_MONGO_URI,
|
||||
mongoReadOnly: false,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test('STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE does not unlock a non-readOnly pipeline', () => {
|
||||
const cfg = makeConfig({ mongoReadOnly: false });
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(cfg, 'dataPipeline', { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true' })
|
||||
).toThrow(PIPELINE_ERROR);
|
||||
});
|
||||
|
||||
test('only the literal string "true" opens the ingestion escape hatch', () => {
|
||||
const cfg = makeConfig({
|
||||
mongoUri: 'mongodb://trading_admin:pw@localhost:27017',
|
||||
mongoReadUri: null,
|
||||
});
|
||||
for (const value of ['1', 'TRUE', 'yes', '']) {
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(cfg, 'dataIngestion', { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: value })
|
||||
).toThrow(WRITE_ERROR);
|
||||
}
|
||||
});
|
||||
|
||||
test('readOnly ingestion-style service on QA :27017 keeps the pre-existing allowance', () => {
|
||||
const cfg = makeConfig({ mongoUri: READ_URI, mongoReadUri: null, mongoReadOnly: true });
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow();
|
||||
expect(() => assertEnvironmentSafety(cfg, 'webApi', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test('unnamed development service writing to QA :27017 is blocked', () => {
|
||||
const cfg = makeConfig({ mongoUri: READ_URI, mongoReadUri: null });
|
||||
expect(() => assertEnvironmentSafety(cfg, undefined, {})).toThrow(/development service "app"/);
|
||||
});
|
||||
|
||||
test('disabled MongoDB skips the Mongo guard for the pipeline', () => {
|
||||
const cfg = makeConfig({
|
||||
mongoEnabled: false,
|
||||
mongoReadUri: 'mongodb://trading_admin:pw@localhost:27017/stock',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test('qa and test environments never apply the dev Mongo guard to the pipeline', () => {
|
||||
for (const environment of ['qa', 'test'] as const) {
|
||||
const cfg = makeConfig({
|
||||
environment,
|
||||
mongoUri: 'mongodb://trading_admin:pw@localhost:27017/stock',
|
||||
mongoReadUri: 'mongodb://trading_admin:pw@localhost:27017/stock',
|
||||
mongoReadOnly: false,
|
||||
mongoDatabase: 'stock',
|
||||
pgDatabase: 'trading_bot',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('enableScheduledJobs defaults off', () => {
|
||||
test('core queueConfigSchema: unset -> false, explicit true -> true', () => {
|
||||
expect(coreQueueConfigSchema.parse({ redis: {} }).enableScheduledJobs).toBe(false);
|
||||
expect(
|
||||
coreQueueConfigSchema.parse({ redis: {}, enableScheduledJobs: true }).enableScheduledJobs
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
test('DI queueConfigSchema: unset -> false, explicit true -> true', () => {
|
||||
expect(diQueueConfigSchema.parse({}).enableScheduledJobs).toBe(false);
|
||||
expect(diQueueConfigSchema.parse({ enableScheduledJobs: true }).enableScheduledJobs).toBe(true);
|
||||
});
|
||||
|
||||
test('stock default.json ships enableScheduledJobs=false', () => {
|
||||
const defaults = JSON.parse(
|
||||
readFileSync(path.resolve(import.meta.dir, '../../apps/stock/config/config/default.json'), 'utf8')
|
||||
);
|
||||
expect(defaults.queue.enableScheduledJobs).toBe(false);
|
||||
});
|
||||
|
||||
test('pipeline and ingestion entrypoints fall back to false, and the pipeline requests mongoReadOnly', () => {
|
||||
for (const app of ['data-pipeline', 'data-ingestion']) {
|
||||
const src = readFileSync(
|
||||
path.resolve(import.meta.dir, `../../apps/stock/${app}/src/index.ts`),
|
||||
'utf8'
|
||||
);
|
||||
expect(src).toContain('enableScheduledJobs: config.queue?.enableScheduledJobs ?? false');
|
||||
expect(src).not.toMatch(/enableScheduledJobs\s*\?\?\s*true/);
|
||||
}
|
||||
const pipelineSrc = readFileSync(
|
||||
path.resolve(import.meta.dir, '../../apps/stock/data-pipeline/src/index.ts'),
|
||||
'utf8'
|
||||
);
|
||||
expect(pipelineSrc).toContain("initializeStockConfig('dataPipeline', { mongoReadOnly: true })");
|
||||
});
|
||||
|
||||
test('env-safety no longer warns on the pipeline admin case', () => {
|
||||
const src = readFileSync(
|
||||
path.resolve(import.meta.dir, '../../apps/stock/config/src/env-safety.ts'),
|
||||
'utf8'
|
||||
);
|
||||
expect(src).not.toContain('logger.warn');
|
||||
});
|
||||
});
|
||||
|
|
@ -3,7 +3,13 @@ import { ConfigManager } from '@stock-bot/config';
|
|||
import { ServiceContainerBuilder } from '@stock-bot/di';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { MongoDBClient } from '@stock-bot/mongodb';
|
||||
import { assertEnvironmentSafety, stockAppSchema, type StockAppConfig } from '@stock-bot/stock-config';
|
||||
import {
|
||||
assertEnvironmentSafety,
|
||||
initializeStockConfig,
|
||||
resetStockConfig,
|
||||
stockAppSchema,
|
||||
type StockAppConfig,
|
||||
} from '@stock-bot/stock-config';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
|
||||
|
|
@ -116,11 +122,131 @@ describe('Environment safety & multi-env isolation', () => {
|
|||
expect(() => assertEnvironmentSafety(cfg, 'dataIngestion', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test('allows development dataPipeline to read QA MongoDB via readUri while writing dev Postgres', () => {
|
||||
const cfg = makeConfig({ environment: 'development' });
|
||||
test('allows development dataPipeline to read QA MongoDB via readUri when readOnly=true', () => {
|
||||
const cfg = makeConfig({ environment: 'development', mongoReadOnly: true });
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).not.toThrow();
|
||||
});
|
||||
|
||||
test('initializeStockConfig applies mongoReadOnly override before safety validation for dev dataPipeline', () => {
|
||||
const envKeys = [
|
||||
'NODE_ENV',
|
||||
'POSTGRES_HOST',
|
||||
'POSTGRES_PORT',
|
||||
'POSTGRES_DB',
|
||||
'POSTGRES_USER',
|
||||
'POSTGRES_PASSWORD',
|
||||
'MONGODB_URI',
|
||||
'MONGODB_READ_URI',
|
||||
'MONGODB_DATABASE',
|
||||
'QUEUE_ENABLE_SCHEDULED_JOBS',
|
||||
'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/stock_dev?authSource=admin';
|
||||
process.env.MONGODB_READ_URI =
|
||||
'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock';
|
||||
process.env.MONGODB_DATABASE = 'stock_dev';
|
||||
delete process.env.QUEUE_ENABLE_SCHEDULED_JOBS;
|
||||
delete process.env.HTTP_PROXY;
|
||||
delete process.env.HTTPS_PROXY;
|
||||
delete process.env.http_proxy;
|
||||
delete process.env.https_proxy;
|
||||
|
||||
resetStockConfig();
|
||||
const cfg = initializeStockConfig('dataPipeline', { mongoReadOnly: true });
|
||||
expect(cfg.database.mongodb.readOnly).toBe(true);
|
||||
expect(cfg.service.serviceName).toBe('data-pipeline');
|
||||
expect(cfg.queue?.enableScheduledJobs).toBe(false);
|
||||
|
||||
// Omitting { mongoReadOnly: true } must fail closed during initializeStockConfig
|
||||
resetStockConfig();
|
||||
expect(() => initializeStockConfig('dataPipeline')).toThrow(
|
||||
/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/
|
||||
);
|
||||
} finally {
|
||||
for (const key of envKeys) {
|
||||
if (savedEnv[key] === undefined) {
|
||||
delete process.env[key];
|
||||
} else {
|
||||
process.env[key] = savedEnv[key];
|
||||
}
|
||||
}
|
||||
resetStockConfig();
|
||||
}
|
||||
});
|
||||
|
||||
test('blocks development dataPipeline from reading QA MongoDB with trading_admin even when readOnly=true or escape hatch is set', () => {
|
||||
const cfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://trading_admin:trading_mongo_dev@localhost:27017/stock?authSource=admin',
|
||||
mongoReadOnly: true,
|
||||
});
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(cfg, 'dataPipeline', { STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true' })
|
||||
).toThrow(/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/);
|
||||
});
|
||||
|
||||
test('blocks development dataPipeline from reading QA MongoDB when readOnly is false', () => {
|
||||
const cfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017/stock?authSource=stock',
|
||||
mongoReadOnly: false,
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(cfg, 'dataPipeline', {})).toThrow(
|
||||
/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/
|
||||
);
|
||||
});
|
||||
|
||||
test('blocks loopback :27017 URI omitting /stock for both dataIngestion and non-readOnly dataPipeline', () => {
|
||||
const ingestionCfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: 'mongodb://trading_admin:pass@localhost:27017',
|
||||
mongoDatabase: 'other_db',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {})).toThrow(
|
||||
/cannot open a writable MongoDB connection to QA MongoDB/
|
||||
);
|
||||
expect(() =>
|
||||
assertEnvironmentSafety(ingestionCfg, 'dataIngestion', {
|
||||
STOCK_BOT_ALLOW_DEV_QA_MONGO_WRITE: 'true',
|
||||
})
|
||||
).not.toThrow();
|
||||
|
||||
const ipv6IngestionCfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoUri: 'mongodb://trading_admin:pass@[::1]:27017',
|
||||
mongoDatabase: 'other_db',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(ipv6IngestionCfg, 'dataIngestion', {})).toThrow(
|
||||
/cannot open a writable MongoDB connection to QA MongoDB/
|
||||
);
|
||||
|
||||
const pipelineCfg = makeConfig({
|
||||
environment: 'development',
|
||||
mongoReadUri: 'mongodb://studio_stock_bot_read:secret@localhost:27017',
|
||||
mongoReadOnly: false,
|
||||
mongoDatabase: 'other_db',
|
||||
});
|
||||
expect(() => assertEnvironmentSafety(pipelineCfg, 'dataPipeline', {})).toThrow(
|
||||
/MONGODB_READ_URI.*studio_stock_bot_read.*mongoReadOnly: true/
|
||||
);
|
||||
});
|
||||
|
||||
test('blocks qa environment from targeting *_dev databases', () => {
|
||||
const cfg = makeConfig({
|
||||
environment: 'qa',
|
||||
|
|
|
|||
1133
test/unit/mongodb-read-only.test.ts
Normal file
1133
test/unit/mongodb-read-only.test.ts
Normal file
File diff suppressed because it is too large
Load diff
Loading…
Add table
Add a link
Reference in a new issue