diff --git a/apps/stock/config/config/default.json b/apps/stock/config/config/default.json index 082a601b..e34d7aca 100644 --- a/apps/stock/config/config/default.json +++ b/apps/stock/config/config/default.json @@ -79,7 +79,7 @@ }, "workers": 5, "concurrency": 2, - "enableScheduledJobs": true, + "enableScheduledJobs": false, "defaultJobOptions": { "attempts": 3, "backoff": { diff --git a/apps/stock/config/src/config-instance.ts b/apps/stock/config/src/config-instance.ts index 67fb5d7b..b5eda87a 100644 --- a/apps/stock/config/src/config-instance.ts +++ b/apps/stock/config/src/config-instance.ts @@ -11,12 +11,18 @@ let configInstance: ConfigManager | 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 diff --git a/apps/stock/config/src/env-safety.ts b/apps/stock/config/src/env-safety.ts index 9d65e22f..d4187560 100644 --- a/apps/stock/config/src/env-safety.ts +++ b/apps/stock/config/src/env-safety.ts @@ -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 = 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( diff --git a/apps/stock/config/src/index.ts b/apps/stock/config/src/index.ts index 28ced46f..82123add 100644 --- a/apps/stock/config/src/index.ts +++ b/apps/stock/config/src/index.ts @@ -9,6 +9,7 @@ export { getProviderConfig, isFeatureEnabled, resetStockConfig, + type InitializeStockConfigOptions, } from './config-instance'; // Export environment safety guard diff --git a/apps/stock/data-ingestion/src/index.ts b/apps/stock/data-ingestion/src/index.ts index f76fc371..9209f6ee 100644 --- a/apps/stock/data-ingestion/src/index.ts +++ b/apps/stock/data-ingestion/src/index.ts @@ -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 }) diff --git a/apps/stock/data-pipeline/src/index.ts b/apps/stock/data-pipeline/src/index.ts index 98cf0e36..5f345689 100644 --- a/apps/stock/data-pipeline/src/index.ts +++ b/apps/stock/data-pipeline/src/index.ts @@ -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 diff --git a/libs/core/config/src/schemas/service.schema.ts b/libs/core/config/src/schemas/service.schema.ts index f92361ca..9986c8ae 100644 --- a/libs/core/config/src/schemas/service.schema.ts +++ b/libs/core/config/src/schemas/service.schema.ts @@ -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), diff --git a/libs/core/config/test/env.loader.test.ts b/libs/core/config/test/env.loader.test.ts index cd8bfe57..b6c37589 100644 --- a/libs/core/config/test/env.loader.test.ts +++ b/libs/core/config/test/env.loader.test.ts @@ -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 | 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 | 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'; diff --git a/libs/core/config/test/schemas.test.ts b/libs/core/config/test/schemas.test.ts index 61414a93..4cee74d2 100644 --- a/libs/core/config/test/schemas.test.ts +++ b/libs/core/config/test/schemas.test.ts @@ -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', () => { diff --git a/libs/core/di/src/config/schemas/service.schema.ts b/libs/core/di/src/config/schemas/service.schema.ts index 73ba1947..1496a99b 100644 --- a/libs/core/di/src/config/schemas/service.schema.ts +++ b/libs/core/di/src/config/schemas/service.schema.ts @@ -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), diff --git a/libs/core/di/src/container/builder.ts b/libs/core/di/src/container/builder.ts index 6ea7bd49..4cd9b5d9 100644 --- a/libs/core/di/src/container/builder.ts +++ b/libs/core/di/src/container/builder.ts @@ -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 = {}; 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({ diff --git a/libs/core/di/src/container/types.ts b/libs/core/di/src/container/types.ts index 15d4ecb8..b5091722 100644 --- a/libs/core/di/src/container/types.ts +++ b/libs/core/di/src/container/types.ts @@ -39,6 +39,7 @@ export interface ServiceContainerOptions { enablePostgres?: boolean; enableCache?: boolean; enableQueue?: boolean; + delayWorkerStart?: boolean; enableBrowser?: boolean; enableProxy?: boolean; } diff --git a/libs/core/di/src/registrations/service.registration.ts b/libs/core/di/src/registrations/service.registration.ts index 7a5b1f26..68e8bc8a 100644 --- a/libs/core/di/src/registrations/service.registration.ts +++ b/libs/core/di/src/registrations/service.registration.ts @@ -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, - 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 { diff --git a/libs/core/di/src/service-application.ts b/libs/core/di/src/service-application.ts index d2a82f38..b63bca36 100644 --- a/libs/core/di/src/service-application.ts +++ b/libs/core/di/src/service-application.ts @@ -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 { + const queueManager = this.resolveOptional('queueManager'); + if (!queueManager) { + return; + } + + const handlerRegistry = this.resolveOptional('handlerRegistry'); + const ownedHandlers = new Set(); + 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 */ diff --git a/libs/core/di/test/container-builder.test.ts b/libs/core/di/test/container-builder.test.ts index 03c5d4db..e630b16a 100644 --- a/libs/core/di/test/container-builder.test.ts +++ b/libs/core/di/test/container-builder.test.ts @@ -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; + }> = []; + 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(); + } + }); }); diff --git a/libs/core/di/test/service-application.test.ts b/libs/core/di/test/service-application.test.ts index 2d07aea8..472f4281 100644 --- a/libs/core/di/test/service-application.test.ts +++ b/libs/core/di/test/service-application.test.ts @@ -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([ + ['{test-service_eod}', ['{test-service_eod}:crawl']], + ['{other-service_sync}', ['{other-service_sync}:daily']], + ]); + const queuedJobs = new Map>([ + [ + '{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', () => { diff --git a/libs/core/queue/src/index.ts b/libs/core/queue/src/index.ts index 9ab2edaa..a7382a22 100644 --- a/libs/core/queue/src/index.ts +++ b/libs/core/queue/src/index.ts @@ -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, diff --git a/libs/core/queue/src/queue-manager.ts b/libs/core/queue/src/queue-manager.ts index ec621569..983270ab 100644 --- a/libs/core/queue/src/queue-manager.ts +++ b/libs/core/queue/src/queue-manager.ts @@ -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; private ioredisConnection?: Redis; private lifecycle: 'running' | 'draining' | 'closed' = 'running'; + private workersStarted = false; private shutdownPromise: Promise | 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(); // 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 { + this.assertConnectionsOpen(); + let totalRemoved = 0; + const seenFullNames = new Set(); + 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 */ diff --git a/libs/core/queue/src/queue.ts b/libs/core/queue/src/queue.ts index 3c303086..46ac78f7 100644 --- a/libs/core/queue/src/queue.ts +++ b/libs/core/queue/src/queue.ts @@ -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>; + +/** + * 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 { + const removedKeys = new Set(); + + 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 { + const removedCount = await removeScheduledJobsFromBullQueue(this.bullQueue); + this.logger.info('Removed scheduled jobs from queue', { + queueName: this.queueName, + removedCount, + }); + return removedCount; + } + /** * Get queue statistics */ diff --git a/libs/core/queue/src/types.ts b/libs/core/queue/src/types.ts index 3e215ab4..692c2a69 100644 --- a/libs/core/queue/src/types.ts +++ b/libs/core/queue/src/types.ts @@ -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 } diff --git a/libs/core/queue/test/queue-class.test.ts b/libs/core/queue/test/queue-class.test.ts index a8d1cd3a..43b886fe 100644 --- a/libs/core/queue/test/queue-class.test.ts +++ b/libs/core/queue/test/queue-class.test.ts @@ -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; + close: ReturnType; + }> = []; + + 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; + }> = []; + + 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); + }); + }); }); diff --git a/libs/data/mongodb/src/client.ts b/libs/data/mongodb/src/client.ts index 2df9c41d..85007288 100644 --- a/libs/data/mongodb/src/client.ts +++ b/libs/data/mongodb/src/client.ts @@ -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([ 'find', 'findOne', @@ -185,21 +210,604 @@ export class MongoDBClient { return this.client.db(databaseName || this.defaultDatabase); } + private createGuardedCursorStream( + cursor: { + next: () => Promise; + close?: () => Promise; + }, + options?: { transform?: (doc: never) => unknown }, + beforeRead?: () => void + ): Readable { + beforeRead?.(); + const transform = options?.transform; + let closePromise: Promise | null = null; + const closeCursor = (): Promise => { + 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, + wrapped: Record + ): Record { + type CursorListener = (...args: unknown[]) => void; + interface TrackedListener { + original: CursorListener; + bound: CursorListener; + once: boolean; + } + const trackedListeners = new Map(); + + 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(cursor: TCursor): TCursor { + const rawCursor = cursor as Record; + + 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 = { + 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; + close?: () => Promise; + }, + 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( + cursor: AggregationCursor + ): AggregationCursor { + const assertCursorPipelineSafe = (): void => { + if (Array.isArray(cursor.pipeline)) { + this.assertReadOnlyPipeline(cursor.pipeline); + } + }; + + const wrapped: Record = { + 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['stream']>[0]) => + this.createGuardedCursorStream( + cursor as unknown as { + next: () => Promise; + close?: () => Promise; + }, + options as { transform?: (doc: never) => unknown } | undefined, + assertCursorPipelineSafe + ) as ReturnType['stream']>, + explain: (...args: Parameters['explain']>) => { + assertCursorPipelineSafe(); + return cursor.explain(...args); + }, + close: (...args: Parameters['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 Promise>>; + 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['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['withReadPreference']>[0]) => { + cursor.withReadPreference(value); + return wrapped; + }, + withReadConcern: (value: Parameters['withReadConcern']>[0]) => { + cursor.withReadConcern(value); + return wrapped; + }, + addCursorFlag: ( + flag: Parameters['addCursorFlag']>[0], + value: boolean + ) => { + cursor.addCursorFlag(flag, value); + return wrapped; + }, + map: (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); + receiver = result; + return result; + }, + clone: () => this.wrapReadOnlyAggregationCursor(cursor.clone()), + }; + + Object.assign( + wrapped, + this.createTrackedCursorEventMethods(cursor as unknown as Record, wrapped) + ); + + return wrapped as unknown as AggregationCursor; + } + private wrapReadOnlyCollection(collection: Collection): Collection { - return new Proxy(collection, { - get: (target, prop, receiver) => { + return new Proxy({} as Collection, { + 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 ( + pipeline: Document[] = [], + options?: AggregateOptions + ) => { + const safePipeline = [...pipeline]; + this.assertReadOnlyPipeline(safePipeline); + return this.wrapReadOnlyAggregationCursor( + collection.aggregate(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 (name: string) => - this.wrapReadOnlyCollection(target.collection(name)); + this.wrapReadOnlyCollection(db.collection(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( diff --git a/test/unit/environment-safety-edge-cases.test.ts b/test/unit/environment-safety-edge-cases.test.ts new file mode 100644 index 00000000..d792d233 --- /dev/null +++ b/test/unit/environment-safety-edge-cases.test.ts @@ -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 = { + 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'); + }); +}); diff --git a/test/unit/environment-safety.test.ts b/test/unit/environment-safety.test.ts index f49c5650..bc0bc88d 100644 --- a/test/unit/environment-safety.test.ts +++ b/test/unit/environment-safety.test.ts @@ -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> = {}; + 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', diff --git a/test/unit/mongodb-read-only.test.ts b/test/unit/mongodb-read-only.test.ts new file mode 100644 index 00000000..ae9de363 --- /dev/null +++ b/test/unit/mongodb-read-only.test.ts @@ -0,0 +1,1133 @@ +import { describe, expect, mock, test } from 'bun:test'; +import { MongoClient } from 'mongodb'; +import { getLogger, setLoggerConfig } from '@stock-bot/logger'; +import { MongoDBClient } from '@stock-bot/mongodb'; + +setLoggerConfig({ logLevel: 'fatal', logConsole: false }); + +function createStubbedClient(readOnly: boolean) { + const logger = getLogger('mongodb-read-only-unit-test'); + + const driverClientSymbol = Symbol('kClient'); + const createCursorStub = (initialPipeline: Record[] = []) => { + const pipeline = [...initialPipeline]; + const docs = [{ _id: 'AAPL', count: 5 }]; + let nextIndex = 0; + + const cursorStub: Record = { + pipeline, + client: { db: mock(() => dbStub) }, + [driverClientSymbol]: { db: mock(() => dbStub) }, + out: mock((target: unknown) => { + pipeline.push({ $out: target }); + return cursorStub; + }), + addStage: mock((stage: Record) => { + pipeline.push(stage); + return cursorStub; + }), + lookup: mock((stage: Record) => { + pipeline.push({ $lookup: stage }); + return cursorStub; + }), + match: mock((stage: Record) => { + pipeline.push({ $match: stage }); + return cursorStub; + }), + project: mock((stage: Record) => { + pipeline.push({ $project: stage }); + return cursorStub; + }), + group: mock((stage: Record) => { + pipeline.push({ $group: stage }); + return cursorStub; + }), + limit: mock((n: number) => { + pipeline.push({ $limit: n }); + return cursorStub; + }), + batchSize: mock(() => cursorStub), + map: mock(() => cursorStub), + clone: mock(() => createCursorStub(pipeline)), + toArray: mock(async () => docs), + next: mock(async () => (nextIndex < docs.length ? docs[nextIndex++] : null)), + [Symbol.asyncIterator]: async function* () { + for (const doc of docs) { + yield doc; + } + }, + [Symbol.asyncDispose]: mock(async () => {}), + }; + return cursorStub; + }; + + let lastCursorStub: ReturnType | null = null; + + const collectionStub = { + collectionName: 'eodPrices', + dbName: 'stock', + namespace: 'stock.eodPrices', + // Safe read methods + find: mock(() => ({ toArray: async () => [{ symbol: 'AAPL', close: 200 }] })), + findOne: mock(async () => ({ symbol: 'AAPL', close: 200 })), + countDocuments: mock(async () => 42), + estimatedDocumentCount: mock(async () => 100), + distinct: mock(async () => ['AAPL', 'MSFT']), + listIndexes: mock(() => ({ toArray: async () => [{ name: '_id_' }] })), + aggregate: mock((pipeline: Record[] = []) => { + lastCursorStub = createCursorStub(pipeline); + return lastCursorStub; + }), + // Write & DDL methods + insertOne: mock(async () => ({ insertedId: 'id-1' })), + insertMany: mock(async () => ({ insertedCount: 1, insertedIds: { 0: 'id-1' } })), + updateOne: mock(async () => ({ matchedCount: 1, modifiedCount: 1, upsertedCount: 0, upsertedId: null })), + updateMany: mock(async () => ({ matchedCount: 1, modifiedCount: 1, upsertedCount: 0, upsertedId: null })), + deleteOne: mock(async () => ({ deletedCount: 1 })), + deleteMany: mock(async () => ({ deletedCount: 1 })), + bulkWrite: mock(async () => ({ upsertedCount: 1, modifiedCount: 0 })), + createIndex: mock(async () => 'symbol_1'), + dropIndex: mock(async () => ({})), + drop: mock(async () => true), + rename: mock(async () => ({})), + }; + + const dbStub = { + databaseName: 'stock', + namespace: 'stock', + collection: mock(() => collectionStub), + listCollections: mock(() => ({ toArray: async () => [{ name: 'eodPrices' }] })), + stats: mock(async () => ({ ok: 1 })), + createCollection: mock(async () => collectionStub), + dropCollection: mock(async () => true), + dropDatabase: mock(async () => true), + command: mock(async () => ({ ok: 1 })), + }; + + const client = new MongoDBClient( + { + host: 'localhost', + port: 27017, + database: 'stock', + readOnly, + }, + logger + ); + + // Inject stubbed driver objects directly so zero network sockets are opened + Object.assign(client, { + client: { db: mock(() => dbStub) }, + db: dbStub, + isConnected: true, + }); + + return { + client, + dbStub, + collectionStub, + driverClientSymbol, + getLastCursorStub: () => lastCursorStub, + }; +} + +function assertZeroMutationCalls( + dbStub: ReturnType['dbStub'], + collectionStub: ReturnType['collectionStub'] +) { + expect(collectionStub.insertOne).not.toHaveBeenCalled(); + expect(collectionStub.insertMany).not.toHaveBeenCalled(); + expect(collectionStub.updateOne).not.toHaveBeenCalled(); + expect(collectionStub.updateMany).not.toHaveBeenCalled(); + expect(collectionStub.deleteOne).not.toHaveBeenCalled(); + expect(collectionStub.deleteMany).not.toHaveBeenCalled(); + expect(collectionStub.bulkWrite).not.toHaveBeenCalled(); + expect(collectionStub.createIndex).not.toHaveBeenCalled(); + expect(collectionStub.dropIndex).not.toHaveBeenCalled(); + expect(collectionStub.drop).not.toHaveBeenCalled(); + expect(collectionStub.rename).not.toHaveBeenCalled(); + expect(dbStub.createCollection).not.toHaveBeenCalled(); + expect(dbStub.dropCollection).not.toHaveBeenCalled(); + expect(dbStub.dropDatabase).not.toHaveBeenCalled(); + expect(dbStub.command).not.toHaveBeenCalled(); +} + +describe('MongoDBClient read-only mode (offline)', () => { + test('blocks all direct client write and DDL methods without calling driver stubs', async () => { + const { client, dbStub, collectionStub } = createStubbedClient(true); + + expect(client.isReadOnly()).toBe(true); + await expect(client.insertOne('x', { symbol: 'AAPL' } as never)).rejects.toThrow(/read-only mode/); + await expect(client.insertMany('x', [{ symbol: 'AAPL' }])).rejects.toThrow(/read-only mode/); + await expect(client.updateOne('x', { symbol: 'AAPL' }, { $set: { close: 1 } })).rejects.toThrow( + /read-only mode/ + ); + await expect(client.updateMany('x', {}, { $set: { close: 1 } })).rejects.toThrow(/read-only mode/); + await expect(client.deleteOne('x', { symbol: 'AAPL' })).rejects.toThrow(/read-only mode/); + await expect(client.deleteMany('x', {})).rejects.toThrow(/read-only mode/); + await expect(client.batchUpsert('x', [{ symbol: 'AAPL' } as never], 'symbol')).rejects.toThrow( + /read-only mode/ + ); + await expect(client.createIndex('x', { symbol: 1 })).rejects.toThrow(/read-only mode/); + await expect(client.dropIndex('x', 'symbol_1')).rejects.toThrow(/read-only mode/); + await expect(client.createCollection('x')).rejects.toThrow(/read-only mode/); + await expect(client.dropCollection('x')).rejects.toThrow(/read-only mode/); + + assertZeroMutationCalls(dbStub, collectionStub); + }); + + test('blocks mutations through getDatabase, getDb, database, getCollection, and collection proxies', () => { + const { client, dbStub, collectionStub } = createStubbedClient(true); + + // Collection write paths through every accessor + expect(() => client.getDatabase().collection('x').insertOne({ a: 1 })).toThrow(/read-only mode/); + expect(() => client.getDb().collection('x').updateOne({ a: 1 }, { $set: { b: 2 } })).toThrow( + /read-only mode/ + ); + expect(() => client.database!.collection('x').deleteMany({})).toThrow(/read-only mode/); + expect(() => client.getCollection('x').insertOne({ a: 1 })).toThrow(/read-only mode/); + expect(() => client.collection('x').bulkWrite([])).toThrow(/read-only mode/); + + // Collection DDL paths + expect(() => client.getCollection('x').createIndex({ symbol: 1 })).toThrow(/read-only mode/); + expect(() => client.collection('x').dropIndex('symbol_1')).toThrow(/read-only mode/); + expect(() => client.getDatabase().collection('x').drop()).toThrow(/read-only mode/); + expect(() => client.getDb().collection('x').rename('y')).toThrow(/read-only mode/); + + // Database DDL/admin paths + expect(() => client.getDatabase().createCollection('x')).toThrow(/read-only mode/); + expect(() => client.getDb().dropCollection('x')).toThrow(/read-only mode/); + expect(() => client.database!.dropDatabase()).toThrow(/read-only mode/); + expect(() => client.getDatabase().command({ dropDatabase: 1 })).toThrow(/read-only mode/); + + assertZeroMutationCalls(dbStub, collectionStub); + }); + + test('blocks $out and $merge aggregation stages (including nested) on client and proxied collections', async () => { + const { client, collectionStub } = createStubbedClient(true); + + const outPipeline = [{ $match: { symbol: 'AAPL' } }, { $out: 'hijacked' }]; + const mergePipeline = [{ $merge: { into: 'hijacked' } }]; + const nestedUnionWith = [ + { $unionWith: { coll: 'other', pipeline: [{ $out: 'hijacked' }] } }, + ]; + const nestedFacet = [ + { $facet: { branch: [{ $merge: { into: 'hijacked' } }] } }, + ]; + + await expect(client.aggregate('x', outPipeline)).rejects.toThrow(/read-only mode/); + await expect(client.aggregate('x', mergePipeline)).rejects.toThrow(/read-only mode/); + await expect(client.aggregate('x', nestedUnionWith)).rejects.toThrow(/read-only mode/); + await expect(client.aggregate('x', nestedFacet)).rejects.toThrow(/read-only mode/); + + expect(() => client.getCollection('x').aggregate(outPipeline)).toThrow(/read-only mode/); + expect(() => client.collection('x').aggregate(mergePipeline)).toThrow(/read-only mode/); + expect(() => client.getDatabase().collection('x').aggregate(nestedUnionWith)).toThrow( + /read-only mode/ + ); + expect(() => client.database!.collection('x').aggregate(nestedFacet)).toThrow(/read-only mode/); + + expect(collectionStub.aggregate).not.toHaveBeenCalled(); + }); + + test('wraps aggregation cursor in a read-only interface blocking fluent write stages and driver client access', async () => { + const { client, driverClientSymbol, getLastCursorStub } = createStubbedClient(true); + + const initialPipeline: Record[] = [{ $match: { symbol: 'AAPL' } }]; + const cursor = client.getDatabase().collection('eodPrices').aggregate(initialPipeline); + const rawCursor = getLastCursorStub()!; + + // Underlying driver client and internal symbols are not exposed + expect((cursor as unknown as Record).client).toBeUndefined(); + expect(Object.getOwnPropertySymbols(cursor)).not.toContain(driverClientSymbol); + + // Mutating caller's input pipeline array or frozen cursor.pipeline cannot inject write stages + initialPipeline.push({ $out: 'hijacked' }); + expect(rawCursor.pipeline).toEqual([{ $match: { symbol: 'AAPL' } }]); + expect(() => (cursor.pipeline as unknown as Record[]).push({ $out: 'hijacked' })).toThrow(); + + // Direct fluent write stages fail closed without touching the underlying cursor + expect(() => cursor.out('hijacked')).toThrow(/read-only mode/); + expect(() => cursor.addStage({ $out: 'hijacked' })).toThrow(/read-only mode/); + expect(() => cursor.addStage({ $merge: { into: 'hijacked' } })).toThrow(/read-only mode/); + expect(() => + cursor.addStage({ $unionWith: { coll: 'other', pipeline: [{ $out: 'hijacked' }] } }) + ).toThrow(/read-only mode/); + expect(() => + cursor.lookup({ from: 'other', pipeline: [{ $merge: { into: 'hijacked' } }], as: 'x' }) + ).toThrow(/read-only mode/); + + // Chained read-only stages, clone(), and map() preserve read-only enforcement + const chained = cursor + .match({ close: { $gt: 100 } }) + .addStage({ $limit: 10 }) + .project({ symbol: 1 }) + .batchSize(100); + expect(() => chained.out('hijacked')).toThrow(/read-only mode/); + expect(() => chained.addStage({ $merge: { into: 'hijacked' } })).toThrow(/read-only mode/); + expect(() => chained.clone().out('hijacked')).toThrow(/read-only mode/); + expect(() => chained.map(doc => doc).addStage({ $out: 'hijacked' })).toThrow(/read-only mode/); + expect(rawCursor.out).not.toHaveBeenCalled(); + + // Safe read iteration (toArray, next, for-await) still works + expect(await chained.toArray()).toEqual([{ _id: 'AAPL', count: 5 }]); + expect(await chained.next()).toEqual({ _id: 'AAPL', count: 5 }); + const iterated: unknown[] = []; + for await (const doc of chained) { + iterated.push(doc); + } + expect(iterated).toEqual([{ _id: 'AAPL', count: 5 }]); + }); + + test('builds aggregation stream from guarded iteration without exposing pinned driver cursor and preserves safe event listeners', async () => { + const logger = getLogger('mongodb-read-only-stream-test'); + // Unconnected real driver client — zero sockets opened + const realMongoClient = new MongoClient('mongodb://127.0.0.1:1/stock'); + const realDb = realMongoClient.db('stock'); + const realCollection = realDb.collection('eodPrices'); + const realCursor = realCollection.aggregate([{ $match: { symbol: 'AAPL' } }]); + + // Confirm the pinned driver's raw stream exposes the unwrapped cursor via `_cursor` + const rawStream = realCursor.stream() as unknown as Record; + expect(rawStream._cursor).toBe(realCursor); + + // Stub next() and close() on the real AggregationCursor so no network I/O occurs + const docs = [ + { _id: 'AAPL', close: 200 }, + { _id: 'MSFT', close: 400 }, + ]; + let index = 0; + const closeMock = mock(async () => {}); + realCursor.next = mock(async () => (index < docs.length ? docs[index++] : null)) as never; + realCursor.close = closeMock as never; + + const fakeDb = { + databaseName: 'stock', + collection: mock(() => ({ + collectionName: 'eodPrices', + aggregate: mock(() => realCursor), + })), + }; + + const client = new MongoDBClient( + { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, + logger + ); + Object.assign(client, { + client: { db: mock(() => fakeDb) }, + db: fakeDb, + isConnected: true, + }); + + const wrappedCursor = client + .getDatabase() + .collection('eodPrices') + .aggregate([{ $match: { symbol: 'AAPL' } }]); + + // Safe EventEmitter methods bind `this` to `wrappedCursor` (never raw `realCursor`), + // track caller references for `listeners()` / `off()` / `removeListener()`, and + // keep the raw driver cursor inaccessible inside regular function listeners. + let closeEvents = 0; + let onceEvents = 0; + const onReceivers: unknown[] = []; + const onceReceivers: unknown[] = []; + + function onCloseListener(this: unknown) { + closeEvents++; + onReceivers.push(this); + expect(this).toBe(wrappedCursor); + expect(this).not.toBe(realCursor); + expect((this as Record).client).toBeUndefined(); + expect(() => (this as { out: (target: string) => unknown }).out('hijacked')).toThrow( + /read-only mode/ + ); + } + + function onceCloseListener(this: unknown) { + onceEvents++; + onceReceivers.push(this); + expect(this).toBe(wrappedCursor); + expect(this).not.toBe(realCursor); + expect((this as Record).client).toBeUndefined(); + expect(() => (this as { out: (target: string) => unknown }).out('hijacked')).toThrow( + /read-only mode/ + ); + } + + const onReturn = wrappedCursor.on('close', onCloseListener); + const onceReturn = wrappedCursor.once('close', onceCloseListener); + expect(onReturn).toBe(wrappedCursor); + expect(onceReturn).toBe(wrappedCursor); + expect(wrappedCursor.listeners('close')).toEqual([onCloseListener, onceCloseListener]); + expect(wrappedCursor.listenerCount('close')).toBe(2); + expect(wrappedCursor.eventNames()).toEqual(['close']); + + realCursor.emit('close'); + expect(closeEvents).toBe(1); + expect(onceEvents).toBe(1); + expect(onReceivers).toEqual([wrappedCursor]); + expect(onceReceivers).toEqual([wrappedCursor]); + expect(wrappedCursor.listeners('close')).toEqual([onCloseListener]); + + realCursor.emit('close'); + expect(closeEvents).toBe(2); + expect(onceEvents).toBe(1); + + // `off` / `removeListener` unregisters using the caller function reference + expect(wrappedCursor.off('close', onCloseListener)).toBe(wrappedCursor); + expect(wrappedCursor.listeners('close')).toEqual([]); + expect(wrappedCursor.listenerCount('close')).toBe(0); + realCursor.emit('close'); + expect(closeEvents).toBe(2); + + // Also verify `removeListener` unregisters a listener registered via `on` + wrappedCursor.on('close', onCloseListener); + expect(wrappedCursor.removeListener('close', onCloseListener)).toBe(wrappedCursor); + expect(wrappedCursor.listeners('close')).toEqual([]); + realCursor.emit('close'); + expect(closeEvents).toBe(2); + + // Wrapped stream must not expose the raw AggregationCursor or MongoClient + const guardedStream = wrappedCursor.stream({ + transform: doc => ({ symbol: doc._id, doubled: Number(doc.close) * 2 }), + }); + const streamRecord = guardedStream as unknown as Record; + expect(streamRecord._cursor).toBeUndefined(); + for (const key of Reflect.ownKeys(guardedStream)) { + expect(streamRecord[key]).not.toBe(realCursor); + expect(streamRecord[key]).not.toBe(realMongoClient); + } + + const streamed: unknown[] = []; + for await (const chunk of guardedStream) { + streamed.push(chunk); + } + expect(streamed).toEqual([ + { symbol: 'AAPL', doubled: 400 }, + { symbol: 'MSFT', doubled: 800 }, + ]); + + // Destroying a guarded stream closes the underlying cursor + index = 0; + closeMock.mockClear(); + const destroyStream = wrappedCursor.stream(); + destroyStream.destroy(); + await new Promise(resolve => setImmediate(resolve)); + expect(closeMock).toHaveBeenCalledTimes(1); + }); + + test('seals find(), listIndexes(), and listCollections() cursors against pinned-driver MongoClient/Db/Collection leaks', async () => { + const logger = getLogger('mongodb-read-only-read-cursors-test'); + // Unconnected real driver client — zero sockets opened + const realMongoClient = new MongoClient('mongodb://127.0.0.1:1/stock'); + const realDb = realMongoClient.db('stock'); + const realCollection = realDb.collection('eodPrices'); + + const roClient = new MongoDBClient( + { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, + logger + ); + Object.assign(roClient, { + client: realMongoClient, + db: realDb, + isConnected: true, + }); + + const assertCursorSealed = ( + cursorObj: unknown, + forbiddenRefs: unknown[] + ): void => { + const record = cursorObj as Record; + expect(record.client).toBeUndefined(); + expect(record.cursorClient).toBeUndefined(); + expect(record.parent).toBeUndefined(); + expect(record.session).toBeUndefined(); + expect(record.cursorSession).toBeUndefined(); + expect(record.server).toBeUndefined(); + expect(record.selectedServer).toBeUndefined(); + expect(record.s).toBeUndefined(); + for (const key of Reflect.ownKeys(cursorObj as object)) { + const value = record[key]; + for (const ref of forbiddenRefs) { + expect(value).not.toBe(ref); + } + } + }; + + // 1. Direct cursors from find(), listIndexes(), and listCollections() do not expose raw driver objects + const findCursor = roClient.getCollection('eodPrices').find({}); + const listIndexesCursor = roClient.getCollection('eodPrices').listIndexes(); + const listCollectionsCursor = roClient.getDatabase().listCollections(); + + assertCursorSealed(findCursor, [realMongoClient, realDb, realCollection]); + assertCursorSealed(listIndexesCursor, [realMongoClient, realDb, realCollection]); + assertCursorSealed(listCollectionsCursor, [realMongoClient, realDb, realCollection]); + + // 2. Fluent modifiers, clone(), and map() on find() remain sealed + const chainedFind = findCursor.sort({ date: -1 }).limit(5).batchSize(10); + expect(chainedFind).toBe(findCursor); + assertCursorSealed(chainedFind, [realMongoClient, realDb, realCollection]); + + const clonedFind = chainedFind.clone(); + expect(clonedFind).not.toBe(chainedFind); + assertCursorSealed(clonedFind, [realMongoClient, realDb, realCollection]); + + const mappedFind = chainedFind.map(doc => doc); + assertCursorSealed(mappedFind, [realMongoClient, realDb, realCollection]); + + // 3 & 4 & 5. Verify guarded stream(), EventEmitter `this` binding, and safe reads on real stubbed cursors + const cursorCases = [ + { + label: 'find', + createRaw: () => realCollection.find({}), + attachAndOpen: (raw: ReturnType) => { + const fakeDb = { + databaseName: 'stock', + collection: mock(() => ({ + collectionName: 'eodPrices', + find: mock(() => raw), + })), + }; + const wrappedClient = new MongoDBClient( + { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, + logger + ); + Object.assign(wrappedClient, { + client: { db: mock(() => fakeDb) }, + db: fakeDb, + isConnected: true, + }); + return wrappedClient.getCollection('eodPrices').find({}); + }, + docs: [ + { _id: '1', symbol: 'AAPL', close: 200 }, + { _id: '2', symbol: 'MSFT', close: 400 }, + ], + }, + { + label: 'listIndexes', + createRaw: () => realCollection.listIndexes(), + attachAndOpen: (raw: ReturnType) => { + const fakeDb = { + databaseName: 'stock', + collection: mock(() => ({ + collectionName: 'eodPrices', + listIndexes: mock(() => raw), + })), + }; + const wrappedClient = new MongoDBClient( + { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, + logger + ); + Object.assign(wrappedClient, { + client: { db: mock(() => fakeDb) }, + db: fakeDb, + isConnected: true, + }); + return wrappedClient.getCollection('eodPrices').listIndexes(); + }, + docs: [{ name: '_id_', key: { _id: 1 } }], + }, + { + label: 'listCollections', + createRaw: () => realDb.listCollections(), + attachAndOpen: (raw: ReturnType) => { + const fakeDb = { + databaseName: 'stock', + listCollections: mock(() => raw), + }; + const wrappedClient = new MongoDBClient( + { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, + logger + ); + Object.assign(wrappedClient, { + client: { db: mock(() => fakeDb) }, + db: fakeDb, + isConnected: true, + }); + return wrappedClient.getDatabase().listCollections(); + }, + docs: [{ name: 'eodPrices', type: 'collection' }], + }, + ]; + + for (const c of cursorCases) { + const rawCursor = c.createRaw(); + // Confirm raw pinned driver cursor does expose the raw MongoClient + expect((rawCursor as unknown as Record).client).toBe(realMongoClient); + + let nextIndex = 0; + const closeMock = mock(async () => {}); + rawCursor.next = mock(async () => + nextIndex < c.docs.length ? c.docs[nextIndex++] : null + ) as never; + rawCursor.toArray = mock(async () => [...c.docs]) as never; + rawCursor.close = closeMock as never; + (rawCursor as unknown as Record)[Symbol.asyncIterator] = async function* () { + for (const doc of c.docs) { + yield doc; + } + }; + + const wrappedCursor = c.attachAndOpen(rawCursor as never); + assertCursorSealed(wrappedCursor, [realMongoClient, realDb, realCollection, rawCursor]); + + // Stream does not expose `_cursor`, raw cursor, or raw MongoClient + const stream = wrappedCursor.stream(); + const streamRecord = stream as unknown as Record; + expect(streamRecord._cursor).toBeUndefined(); + for (const key of Reflect.ownKeys(stream)) { + expect(streamRecord[key]).not.toBe(rawCursor); + expect(streamRecord[key]).not.toBe(realMongoClient); + } + const streamed: unknown[] = []; + for await (const doc of stream) { + streamed.push(doc); + } + expect(streamed).toEqual(c.docs); + + // Destroying stream calls close() + nextIndex = 0; + closeMock.mockClear(); + const destroyable = wrappedCursor.stream(); + destroyable.destroy(); + await new Promise(resolve => setImmediate(resolve)); + expect(closeMock).toHaveBeenCalledTimes(1); + + // EventEmitter listeners receive wrappedCursor as `this` (never rawCursor) + let onCalls = 0; + let onceCalls = 0; + function onClose(this: unknown) { + onCalls++; + expect(this).toBe(wrappedCursor); + expect(this).not.toBe(rawCursor); + expect((this as Record).client).toBeUndefined(); + } + function onceClose(this: unknown) { + onceCalls++; + expect(this).toBe(wrappedCursor); + expect(this).not.toBe(rawCursor); + expect((this as Record).client).toBeUndefined(); + } + wrappedCursor.on('close', onClose); + wrappedCursor.once('close', onceClose); + expect(wrappedCursor.listeners('close')).toEqual([onClose, onceClose]); + + rawCursor.emit('close'); + expect(onCalls).toBe(1); + expect(onceCalls).toBe(1); + expect(wrappedCursor.listeners('close')).toEqual([onClose]); + + wrappedCursor.off('close', onClose); + rawCursor.emit('close'); + expect(onCalls).toBe(1); + + // Safe read methods work on real stubbed cursors + expect(await wrappedCursor.toArray()).toEqual(c.docs); + nextIndex = 0; + expect(await wrappedCursor.next()).toEqual(c.docs[0]); + const iterated: unknown[] = []; + for await (const doc of wrappedCursor) { + iterated.push(doc); + } + expect(iterated).toEqual(c.docs); + } + }); + + test('seals map() and forEach() callback receivers on pinned-driver find, listIndexes, listCollections, and aggregate cursors', async () => { + const logger = getLogger('mongodb-read-only-map-receiver-test'); + const realMongoClient = new MongoClient('mongodb://127.0.0.1:1/stock'); + const realDb = realMongoClient.db('stock'); + const realCollection = realDb.collection('eodPrices'); + + const seedCursorDocuments = (rawCursor: object, docs: Record[]) => { + const queue = [...docs]; + const raw = rawCursor as Record; + raw.documents = { + get length() { + return queue.length; + }, + shift() { + return queue.shift() ?? null; + }, + clear() { + queue.length = 0; + }, + }; + raw.fetchBatch = mock(async () => { + raw.isClosed = true; + }); + raw.close = mock(async () => { + raw.isClosed = true; + }); + }; + + const wrapRawCursor = ( + kind: 'find' | 'listIndexes' | 'listCollections' | 'aggregate', + rawCursor: object + ) => { + const fakeDb = { + databaseName: 'stock', + listCollections: mock(() => rawCursor), + collection: mock(() => ({ + collectionName: 'eodPrices', + find: mock(() => rawCursor), + listIndexes: mock(() => rawCursor), + aggregate: mock(() => rawCursor), + })), + }; + const wrappedClient = new MongoDBClient( + { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, + logger + ); + Object.assign(wrappedClient, { + client: { db: mock(() => fakeDb) }, + db: fakeDb, + isConnected: true, + }); + + if (kind === 'find') { + return wrappedClient.getCollection('eodPrices').find({}); + } + if (kind === 'listIndexes') { + return wrappedClient.getCollection('eodPrices').listIndexes(); + } + if (kind === 'listCollections') { + return wrappedClient.getDatabase().listCollections(); + } + return wrappedClient.getDatabase().collection('eodPrices').aggregate([{ $match: {} }]); + }; + + const kinds: Array<{ + kind: 'find' | 'listIndexes' | 'listCollections' | 'aggregate'; + createRaw: () => object; + docs: Record[]; + }> = [ + { + kind: 'find', + createRaw: () => realCollection.find({}), + docs: [ + { _id: '1', symbol: 'AAPL', close: 200 }, + { _id: '2', symbol: 'MSFT', close: 400 }, + ], + }, + { + kind: 'listIndexes', + createRaw: () => realCollection.listIndexes(), + docs: [ + { name: '_id_', key: { _id: 1 } }, + { name: 'symbol_1', key: { symbol: 1 } }, + ], + }, + { + kind: 'listCollections', + createRaw: () => realDb.listCollections(), + docs: [ + { name: 'eodPrices', type: 'collection' }, + { name: 'splits', type: 'collection' }, + ], + }, + { + kind: 'aggregate', + createRaw: () => realCollection.aggregate([{ $match: {} }]), + docs: [ + { _id: 'AAPL', close: 200 }, + { _id: 'MSFT', close: 400 }, + ], + }, + ]; + + const assertGuardedReceiver = ( + receiver: unknown, + expectedCursor: unknown, + rawCursor: object, + isAggregate: boolean + ) => { + expect(receiver).toBe(expectedCursor); + expect(receiver).not.toBe(rawCursor); + const record = receiver as Record; + expect(record.client).toBeUndefined(); + expect(record.parent).toBeUndefined(); + if (isAggregate) { + expect(() => (receiver as { out: (target: string) => unknown }).out('x')).toThrow( + /read-only mode/ + ); + } + }; + + // Exercise map() across next(), toArray(), for-await, and stream() on every cursor kind + const modes: Array<'next' | 'toArray' | 'forAwait' | 'stream'> = [ + 'next', + 'toArray', + 'forAwait', + 'stream', + ]; + + for (const { kind, createRaw, docs } of kinds) { + for (const mode of modes) { + const rawCursor = createRaw(); + seedCursorDocuments(rawCursor, docs); + const wrapped = wrapRawCursor(kind, rawCursor) as { + map: (fn: (doc: Record) => unknown) => Record; + }; + + const receivers: unknown[] = []; + const mappedCursor = wrapped.map(function (this: unknown, doc: Record) { + receivers.push(this); + assertGuardedReceiver(this, mappedCursor, rawCursor, kind === 'aggregate'); + return { mapped: true, doc }; + }); + + const results: unknown[] = []; + if (mode === 'next') { + while (true) { + const item = await (mappedCursor.next as () => Promise)(); + if (item == null) break; + results.push(item); + } + } else if (mode === 'toArray') { + results.push(...(await (mappedCursor.toArray as () => Promise)())); + } else if (mode === 'forAwait') { + for await (const item of mappedCursor as AsyncIterable) { + results.push(item); + } + } else { + for await (const item of (mappedCursor.stream as () => AsyncIterable)()) { + results.push(item); + } + } + + expect(results).toEqual(docs.map(doc => ({ mapped: true, doc }))); + expect(receivers.length).toBe(docs.length); + } + + // Chained map().map() gives every transform the guarded cursor as `this` + const rawChained = createRaw(); + seedCursorDocuments(rawChained, docs); + const wrappedChained = wrapRawCursor(kind, rawChained) as { + map: (fn: (doc: unknown) => unknown) => { + map: (fn: (doc: unknown) => unknown) => { toArray: () => Promise }; + }; + }; + const firstReceivers: unknown[] = []; + const secondReceivers: unknown[] = []; + const step1 = wrappedChained.map(function (this: unknown, doc: unknown) { + firstReceivers.push(this); + assertGuardedReceiver(this, step1, rawChained, kind === 'aggregate'); + return { step: 1, doc }; + }); + const step2 = step1.map(function (this: unknown, doc: unknown) { + secondReceivers.push(this); + assertGuardedReceiver(this, step2, rawChained, kind === 'aggregate'); + return { step: 2, prev: doc }; + }); + const chainedOut = await step2.toArray(); + expect(chainedOut).toEqual(docs.map(doc => ({ step: 2, prev: { step: 1, doc } }))); + expect(firstReceivers.length).toBe(docs.length); + expect(secondReceivers.length).toBe(docs.length); + + // clone() after map() calls the pinned driver's real clone(), stays sealed, leaves the + // original transform uncalled when iterating the clone, and binds a new map() on the clone + // to the cloned wrapper + const rawOriginal = createRaw(); + const wrappedOriginal = wrapRawCursor(kind, rawOriginal) as { + map: (fn: (doc: unknown) => unknown) => { + clone: () => { + toArray: () => Promise; + map: (fn: (doc: unknown) => unknown) => { toArray: () => Promise }; + }; + }; + }; + const originalTransformCalls: unknown[] = []; + const mappedOriginal = wrappedOriginal.map(function (this: unknown, doc: unknown) { + originalTransformCalls.push(this); + assertGuardedReceiver(this, mappedOriginal, rawOriginal, kind === 'aggregate'); + return { original: true, doc }; + }); + const realCloneFn = (rawOriginal as { clone: () => object }).clone; + let capturedRawClone: object | undefined; + (rawOriginal as Record).clone = () => { + const realCloned = realCloneFn.call(rawOriginal); + capturedRawClone = realCloned; + seedCursorDocuments(realCloned, docs); + return realCloned; + }; + const clonedForRead = mappedOriginal.clone(); + expect(capturedRawClone).toBeDefined(); + expect((clonedForRead as unknown as Record).client).toBeUndefined(); + expect((clonedForRead as unknown as Record).parent).toBeUndefined(); + expect(await clonedForRead.toArray()).toEqual(docs); + expect(originalTransformCalls.length).toBe(0); + + const clonedForMap = mappedOriginal.clone(); + const rawCloneForMap = capturedRawClone!; + const cloneReceivers: unknown[] = []; + const mappedClone = clonedForMap.map(function (this: unknown, doc: unknown) { + cloneReceivers.push(this); + assertGuardedReceiver(this, mappedClone, rawCloneForMap, kind === 'aggregate'); + return { cloned: true, doc }; + }); + expect(await mappedClone.toArray()).toEqual(docs.map(doc => ({ cloned: true, doc }))); + expect(cloneReceivers.length).toBe(docs.length); + expect(originalTransformCalls.length).toBe(0); + + // forEach() also binds `this` to the wrapped cursor (never rawCursor) + const rawForEach = createRaw(); + seedCursorDocuments(rawForEach, docs); + const wrappedForEach = wrapRawCursor(kind, rawForEach) as { + forEach: (fn: (doc: unknown) => void) => Promise; + }; + const forEachReceivers: unknown[] = []; + const visited: unknown[] = []; + await wrappedForEach.forEach(function (this: unknown, doc: unknown) { + forEachReceivers.push(this); + assertGuardedReceiver(this, wrappedForEach, rawForEach, kind === 'aggregate'); + visited.push(doc); + }); + expect(visited).toEqual(docs); + expect(forEachReceivers.length).toBe(docs.length); + } + }); + + test('skips null and undefined stream transform results without truncating exports, closes once on EOF, and propagates transform errors', async () => { + const logger = getLogger('mongodb-read-only-stream-transform-test'); + const realMongoClient = new MongoClient('mongodb://127.0.0.1:1/stock'); + const realCollection = realMongoClient.db('stock').collection('eodPrices'); + + const rows = [ + { _id: '1', symbol: 'AAPL', close: 200 }, + { _id: '2', symbol: 'SKIP', close: 0 }, + { _id: '3', symbol: 'MSFT', close: 400 }, + ]; + + const openWrappedFind = (rawCursor: object) => { + const fakeDb = { + databaseName: 'stock', + collection: mock(() => ({ + collectionName: 'eodPrices', + find: mock(() => rawCursor), + })), + }; + const wrappedClient = new MongoDBClient( + { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, + logger + ); + Object.assign(wrappedClient, { + client: { db: mock(() => fakeDb) }, + db: fakeDb, + isConnected: true, + }); + return wrappedClient.getCollection('eodPrices').find({}); + }; + + for (const skipValue of [null, undefined] as const) { + const rawCursor = realCollection.find({}); + let index = 0; + let exhausted = false; + const closeMock = mock(async () => {}); + rawCursor.next = mock(async () => { + if (index < rows.length) { + return rows[index++]; + } + exhausted = true; + return null; + }) as never; + rawCursor.close = closeMock as never; + + const wrapped = openWrappedFind(rawCursor); + const stream = wrapped.stream({ + transform: (doc: Record) => + doc.symbol === 'SKIP' ? skipValue : { symbol: doc.symbol, close: doc.close }, + }); + + const emitted: unknown[] = []; + let endFiredWhenExhausted = false; + stream.on('end', () => { + endFiredWhenExhausted = exhausted; + }); + + for await (const chunk of stream) { + emitted.push(chunk); + } + + expect(emitted).toEqual([ + { symbol: 'AAPL', close: 200 }, + { symbol: 'MSFT', close: 400 }, + ]); + expect(endFiredWhenExhausted).toBe(true); + expect(closeMock).toHaveBeenCalledTimes(1); + } + + // Mapped-then-streamed cursor skips nullish stream transforms while sealing map() receiver + { + const rawCursor = realCollection.find({}); + const queue = [...rows]; + const raw = rawCursor as unknown as Record; + const closeMock = mock(async () => { + raw.isClosed = true; + }); + raw.documents = { + get length() { + return queue.length; + }, + shift() { + return queue.shift() ?? null; + }, + clear() { + queue.length = 0; + }, + }; + raw.fetchBatch = mock(async () => { + raw.isClosed = true; + }); + raw.close = closeMock; + + const wrapped = openWrappedFind(rawCursor); + const mapReceivers: unknown[] = []; + const mapped = wrapped.map(function (this: unknown, doc: Record) { + mapReceivers.push(this); + expect(this).toBe(mapped); + expect((this as Record).client).toBeUndefined(); + return { sym: doc.symbol, doubled: Number(doc.close) * 2 }; + }); + + const emitted: unknown[] = []; + for await (const chunk of mapped.stream({ + transform: (doc: { sym: unknown; doubled: number }) => + doc.sym === 'SKIP' ? null : doc, + })) { + emitted.push(chunk); + } + + expect(emitted).toEqual([ + { sym: 'AAPL', doubled: 400 }, + { sym: 'MSFT', doubled: 800 }, + ]); + expect(mapReceivers.length).toBe(3); + expect(closeMock).toHaveBeenCalledTimes(1); + } + + // Error case: throwing transform destroys the stream with that error and closes the cursor once + { + const rawCursor = realCollection.find({}); + let index = 0; + const closeMock = mock(async () => {}); + rawCursor.next = mock(async () => (index < rows.length ? rows[index++] : null)) as never; + rawCursor.close = closeMock as never; + + const wrapped = openWrappedFind(rawCursor); + const boom = new Error('transform boom'); + const stream = wrapped.stream({ + transform: (doc: Record) => { + if (doc.symbol === 'SKIP') { + throw boom; + } + return doc; + }, + }); + + const emitted: unknown[] = []; + let caughtError: unknown = null; + try { + for await (const chunk of stream) { + emitted.push(chunk); + } + } catch (err) { + caughtError = err; + } + + expect(emitted).toEqual([rows[0]]); + expect(caughtError).toBe(boom); + expect(stream.destroyed).toBe(true); + expect(closeMock).toHaveBeenCalledTimes(1); + } + }); + + test('hides raw MongoClient/Db/Collection via property descriptor reflection on read-only proxies', () => { + const logger = getLogger('mongodb-read-only-reflection-test'); + const realMongoClient = new MongoClient('mongodb://127.0.0.1:1/stock'); + const realDb = realMongoClient.db('stock'); + + const wrappedClient = new MongoDBClient( + { host: '127.0.0.1', port: 1, database: 'stock', readOnly: true }, + logger + ); + Object.assign(wrappedClient, { + client: realMongoClient, + db: realDb, + isConnected: true, + }); + + const roDb = wrappedClient.getDatabase(); + const roCollection = wrappedClient.getCollection('eodPrices'); + + for (const key of ['client', 's'] as const) { + expect(Object.getOwnPropertyDescriptor(roDb, key)).toBeUndefined(); + } + for (const key of ['client', 'db', 's'] as const) { + expect(Object.getOwnPropertyDescriptor(roCollection, key)).toBeUndefined(); + } + expect(Reflect.ownKeys(roDb)).toEqual([]); + expect(Reflect.ownKeys(roCollection)).toEqual([]); + + // Safe read-only metadata getters still resolve properly on the pinned driver + expect(roDb.databaseName).toBe('stock'); + expect(roDb.namespace).toBe('stock'); + expect(roCollection.collectionName).toBe('eodPrices'); + expect(roCollection.dbName).toBe('stock'); + expect(roCollection.namespace).toBe('stock.eodPrices'); + }); + + test('passes through safe read operations on client and proxies', async () => { + const { client, dbStub, collectionStub } = createStubbedClient(true); + + expect(await client.find('eodPrices', { symbol: 'AAPL' })).toEqual([ + { symbol: 'AAPL', close: 200 }, + ]); + expect(await client.findOne('eodPrices', { symbol: 'AAPL' })).toEqual({ + symbol: 'AAPL', + close: 200, + }); + expect(await client.countDocuments('eodPrices', {})).toBe(42); + expect(await client.listIndexes('eodPrices')).toEqual([{ name: '_id_' }]); + expect(await client.listCollections()).toEqual([{ name: 'eodPrices' }]); + expect(await client.aggregate('eodPrices', [{ $match: { symbol: 'AAPL' } }])).toEqual([ + { _id: 'AAPL', count: 5 }, + ]); + + // Proxied read methods + expect(await client.getCollection('eodPrices').estimatedDocumentCount()).toBe(100); + expect(await client.collection('eodPrices').distinct('symbol')).toEqual(['AAPL', 'MSFT']); + expect( + await client.getDatabase().collection('eodPrices').find({ symbol: 'AAPL' }).toArray() + ).toEqual([{ symbol: 'AAPL', close: 200 }]); + expect( + await client + .getDb() + .collection('eodPrices') + .aggregate([{ $group: { _id: '$symbol' } }]) + .toArray() + ).toEqual([{ _id: 'AAPL', count: 5 }]); + + expect(collectionStub.find).toHaveBeenCalledTimes(2); + expect(collectionStub.findOne).toHaveBeenCalledTimes(1); + expect(collectionStub.countDocuments).toHaveBeenCalledTimes(1); + expect(collectionStub.estimatedDocumentCount).toHaveBeenCalledTimes(1); + expect(collectionStub.distinct).toHaveBeenCalledTimes(1); + expect(collectionStub.listIndexes).toHaveBeenCalledTimes(1); + expect(collectionStub.aggregate).toHaveBeenCalledTimes(2); + expect(dbStub.listCollections).toHaveBeenCalledTimes(1); + }); + + test('allows writes when readOnly is false (control check)', async () => { + const { client, dbStub, collectionStub } = createStubbedClient(false); + + expect(client.isReadOnly()).toBe(false); + const inserted = await client.insertOne('eodPrices', { symbol: 'AAPL' } as never); + expect((inserted as Record)._id).toBe('id-1'); + await client.getDatabase().collection('eodPrices').insertOne({ symbol: 'MSFT' }); + await client.getDatabase().createCollection('tmp'); + + expect(collectionStub.insertOne).toHaveBeenCalledTimes(2); + expect(dbStub.createCollection).toHaveBeenCalledTimes(1); + }); +});