T-7: M0.3a — Harden dev Mongo safety: env-safety throws on unsafe data-pipeline QA reads, scheduled jobs default off, read-only bypass tests
This commit is contained in:
parent
abbab4b5a8
commit
0e5ebbd62f
9 changed files with 425 additions and 29 deletions
|
|
@ -73,6 +73,7 @@ export function registerApplicationServices(
|
|||
defaultJobOptions: defined(config.queue).defaultJobOptions,
|
||||
},
|
||||
enableScheduledJobs: defined(config.queue).enableScheduledJobs ?? false,
|
||||
delayWorkerStart: true,
|
||||
autoDiscoverHandlers: true,
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -517,6 +517,12 @@ export class ServiceApplication {
|
|||
}
|
||||
}
|
||||
|
||||
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));
|
||||
}
|
||||
|
|
|
|||
|
|
@ -505,6 +505,102 @@ describe('ServiceApplication', () => {
|
|||
]);
|
||||
}
|
||||
});
|
||||
|
||||
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', () => {
|
||||
|
|
|
|||
|
|
@ -36,6 +36,7 @@ export class QueueManager {
|
|||
private redisConnection: ReturnType<typeof getRedisConnection>;
|
||||
private ioredisConnection?: Redis;
|
||||
private lifecycle: 'running' | 'draining' | 'closed' = 'running';
|
||||
private workersStarted = false;
|
||||
private shutdownPromise: Promise<void> | null = null;
|
||||
private config: QueueManagerConfig;
|
||||
private readonly logger: Logger;
|
||||
|
|
@ -154,11 +155,13 @@ 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,
|
||||
|
|
@ -183,7 +186,7 @@ export class QueueManager {
|
|||
workers: workers,
|
||||
concurrency: concurrency,
|
||||
handlerRegistryProvided: !!this.handlerRegistry,
|
||||
willStartWorkers: workers > 0,
|
||||
willStartWorkers: shouldStartWorker,
|
||||
isOwnQueue,
|
||||
serviceName: this.serviceName,
|
||||
});
|
||||
|
|
@ -519,8 +522,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})`
|
||||
|
|
@ -531,7 +538,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,
|
||||
|
|
|
|||
|
|
@ -42,7 +42,7 @@ export async function removeScheduledJobsFromBullQueue(
|
|||
}
|
||||
}
|
||||
|
||||
const pendingJobs = await bullQueue.getJobs(['waiting', 'delayed']);
|
||||
const pendingJobs = await bullQueue.getJobs(['waiting', 'delayed', 'prioritized']);
|
||||
for (const job of pendingJobs) {
|
||||
const repeatKey = job?.repeatJobKey ?? job?.opts?.repeatJobKey;
|
||||
if (repeatKey) {
|
||||
|
|
|
|||
|
|
@ -72,6 +72,7 @@ export interface QueueManagerConfig {
|
|||
redis: RedisConfig;
|
||||
defaultQueueOptions?: QueueOptions;
|
||||
enableScheduledJobs?: boolean;
|
||||
delayWorkerStart?: boolean;
|
||||
serviceName?: string; // For service discovery and namespacing
|
||||
autoDiscoverHandlers?: boolean; // Auto-discover queue routes from handler registry
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,6 @@
|
|||
import { describe, expect, it, mock } from 'bun:test';
|
||||
import { Queue, removeScheduledJobsFromBullQueue } from '../src/queue';
|
||||
import { QueueManager } from '../src/queue-manager';
|
||||
import type { QueueWorkerConfig, RedisConfig } from '../src/types';
|
||||
|
||||
describe('Queue Class', () => {
|
||||
|
|
@ -124,51 +125,115 @@ describe('Queue Class', () => {
|
|||
});
|
||||
|
||||
describe('scheduled job reconciliation', () => {
|
||||
it('removes repeatable jobs, job schedulers, and pending repeat instances while preserving manual jobs', async () => {
|
||||
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_eod}:crawl', name: 'crawl' },
|
||||
{ key: '{data-ingestion_te}:crawlScheduler', name: 'crawlScheduler' },
|
||||
]),
|
||||
removeRepeatableByKey: mock(async (key: string) => {
|
||||
removedRepeatKeys.push(key);
|
||||
return true;
|
||||
}),
|
||||
getJobSchedulers: mock(async () => [
|
||||
{ key: '{data-ingestion_eod}:crawl', name: 'crawl' },
|
||||
{ key: '{data-ingestion_eod}:intraday', name: 'intraday' },
|
||||
{ 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 () => [
|
||||
{
|
||||
id: 'repeat-job-1',
|
||||
repeatJobKey: '{data-ingestion_eod}:crawl',
|
||||
remove: mock(async () => {
|
||||
removedJobIds.push('repeat-job-1');
|
||||
}),
|
||||
},
|
||||
{
|
||||
id: 'manual-eod-job-1',
|
||||
opts: {},
|
||||
remove: mock(async () => {
|
||||
removedJobIds.push('manual-eod-job-1');
|
||||
}),
|
||||
},
|
||||
]),
|
||||
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_eod}:crawl']);
|
||||
expect(removedSchedulerKeys).toEqual(['{data-ingestion_eod}:intraday']);
|
||||
expect(removedJobIds).toEqual(['repeat-job-1']);
|
||||
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 manager = new QueueManager(
|
||||
{
|
||||
serviceName: 'data-ingestion',
|
||||
redis: { ...mockRedisConfig, maxRetriesPerRequest: 1 },
|
||||
delayWorkerStart: true,
|
||||
defaultQueueOptions: { workers: 1, concurrency: 2 },
|
||||
},
|
||||
undefined,
|
||||
mockLogger
|
||||
);
|
||||
|
||||
// Suppress background connection error logs in offline test environment
|
||||
const ioRedis = (
|
||||
manager as unknown as {
|
||||
ioredisConnection?: { on: (e: string, cb: () => void) => void; disconnect: () => void };
|
||||
}
|
||||
).ioredisConnection;
|
||||
ioRedis?.on('error', () => {});
|
||||
|
||||
try {
|
||||
const teQueue = manager.getQueue('te');
|
||||
expect(teQueue.getName()).toBe('{data-ingestion_te}');
|
||||
// Queue must stay workerless while handlers initialize and schedules reconcile
|
||||
expect(teQueue.getWorkerCount()).toBe(0);
|
||||
|
||||
const startSpy = mock(() => {});
|
||||
teQueue.startWorkersManually = startSpy;
|
||||
|
||||
manager.startAllWorkers();
|
||||
expect(startSpy).toHaveBeenCalledTimes(1);
|
||||
expect(startSpy).toHaveBeenCalledWith(1, 2);
|
||||
} finally {
|
||||
ioRedis?.disconnect();
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
import { Readable } from 'node:stream';
|
||||
import type {
|
||||
AggregateOptions,
|
||||
AggregationCursor,
|
||||
|
|
@ -241,9 +242,75 @@ export class MongoDBClient {
|
|||
assertCursorPipelineSafe();
|
||||
return cursor.forEach(iterator);
|
||||
},
|
||||
stream: (...args: Parameters<AggregationCursor<T>['stream']>) => {
|
||||
stream: (options?: Parameters<AggregationCursor<T>['stream']>[0]) => {
|
||||
assertCursorPipelineSafe();
|
||||
return cursor.stream(...args);
|
||||
const transform = options?.transform;
|
||||
let readInProgress = false;
|
||||
|
||||
const readable = new Readable({
|
||||
objectMode: true,
|
||||
autoDestroy: false,
|
||||
highWaterMark: 1,
|
||||
read() {
|
||||
if (readInProgress) {
|
||||
return;
|
||||
}
|
||||
readInProgress = true;
|
||||
const readNext = (): void => {
|
||||
try {
|
||||
assertCursorPipelineSafe();
|
||||
} catch (err) {
|
||||
readInProgress = false;
|
||||
this.destroy(err instanceof Error ? err : new Error(String(err)));
|
||||
return;
|
||||
}
|
||||
|
||||
cursor.next().then(
|
||||
doc => {
|
||||
if (doc == null) {
|
||||
readInProgress = false;
|
||||
this.push(null);
|
||||
return;
|
||||
}
|
||||
if (this.destroyed) {
|
||||
readInProgress = false;
|
||||
cursor.close().catch(() => {});
|
||||
return;
|
||||
}
|
||||
let output: unknown = doc;
|
||||
if (transform) {
|
||||
try {
|
||||
output = transform(doc);
|
||||
} catch (err) {
|
||||
readInProgress = false;
|
||||
this.destroy(err instanceof Error ? err : new Error(String(err)));
|
||||
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) {
|
||||
cursor.close().then(
|
||||
() => callback(error),
|
||||
closeError =>
|
||||
callback(closeError instanceof Error ? closeError : new Error(String(closeError)))
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
return readable as ReturnType<AggregationCursor<T>['stream']>;
|
||||
},
|
||||
explain: (...args: Parameters<AggregationCursor<T>['explain']>) => {
|
||||
assertCursorPipelineSafe();
|
||||
|
|
@ -345,6 +412,69 @@ export class MongoDBClient {
|
|||
: this.wrapReadOnlyAggregationCursor(mapped as unknown as AggregationCursor<Document>);
|
||||
},
|
||||
clone: () => this.wrapReadOnlyAggregationCursor(cursor.clone()),
|
||||
// Safe EventEmitter delegation without exposing the raw driver cursor
|
||||
on: (event: string | symbol, listener: (...args: unknown[]) => void) => {
|
||||
if (typeof cursor.on === 'function') {
|
||||
cursor.on(event as never, listener as never);
|
||||
}
|
||||
return wrapped;
|
||||
},
|
||||
once: (event: string | symbol, listener: (...args: unknown[]) => void) => {
|
||||
if (typeof cursor.once === 'function') {
|
||||
cursor.once(event as never, listener as never);
|
||||
}
|
||||
return wrapped;
|
||||
},
|
||||
off: (event: string | symbol, listener: (...args: unknown[]) => void) => {
|
||||
if (typeof cursor.off === 'function') {
|
||||
cursor.off(event as never, listener as never);
|
||||
}
|
||||
return wrapped;
|
||||
},
|
||||
addListener: (event: string | symbol, listener: (...args: unknown[]) => void) => {
|
||||
if (typeof cursor.addListener === 'function') {
|
||||
cursor.addListener(event as never, listener as never);
|
||||
}
|
||||
return wrapped;
|
||||
},
|
||||
removeListener: (event: string | symbol, listener: (...args: unknown[]) => void) => {
|
||||
if (typeof cursor.removeListener === 'function') {
|
||||
cursor.removeListener(event as never, listener as never);
|
||||
}
|
||||
return wrapped;
|
||||
},
|
||||
removeAllListeners: (event?: string | symbol) => {
|
||||
if (typeof cursor.removeAllListeners === 'function') {
|
||||
cursor.removeAllListeners(event as never);
|
||||
}
|
||||
return wrapped;
|
||||
},
|
||||
prependListener: (event: string | symbol, listener: (...args: unknown[]) => void) => {
|
||||
if (typeof cursor.prependListener === 'function') {
|
||||
cursor.prependListener(event as never, listener as never);
|
||||
}
|
||||
return wrapped;
|
||||
},
|
||||
prependOnceListener: (event: string | symbol, listener: (...args: unknown[]) => void) => {
|
||||
if (typeof cursor.prependOnceListener === 'function') {
|
||||
cursor.prependOnceListener(event as never, listener as never);
|
||||
}
|
||||
return wrapped;
|
||||
},
|
||||
setMaxListeners: (n: number) => {
|
||||
if (typeof cursor.setMaxListeners === 'function') {
|
||||
cursor.setMaxListeners(n);
|
||||
}
|
||||
return wrapped;
|
||||
},
|
||||
getMaxListeners: () => (typeof cursor.getMaxListeners === 'function' ? cursor.getMaxListeners() : 10),
|
||||
listeners: (event: string | symbol) =>
|
||||
typeof cursor.listeners === 'function' ? cursor.listeners(event as never) : [],
|
||||
rawListeners: (event: string | symbol) =>
|
||||
typeof cursor.rawListeners === 'function' ? cursor.rawListeners(event as never) : [],
|
||||
listenerCount: (event: string | symbol) =>
|
||||
typeof cursor.listenerCount === 'function' ? cursor.listenerCount(event as never) : 0,
|
||||
eventNames: () => (typeof cursor.eventNames === 'function' ? cursor.eventNames() : []),
|
||||
};
|
||||
|
||||
return wrapped as unknown as AggregationCursor<T>;
|
||||
|
|
|
|||
|
|
@ -1,4 +1,5 @@
|
|||
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';
|
||||
|
||||
|
|
@ -277,6 +278,95 @@ describe('MongoDBClient read-only mode (offline)', () => {
|
|||
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<string, unknown>;
|
||||
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 work and return the wrapped cursor (never raw realCursor)
|
||||
let closeEvents = 0;
|
||||
let onceEvents = 0;
|
||||
const onReturn = wrappedCursor.on('close', () => {
|
||||
closeEvents++;
|
||||
});
|
||||
const onceReturn = wrappedCursor.once('close', () => {
|
||||
onceEvents++;
|
||||
});
|
||||
expect(onReturn).toBe(wrappedCursor);
|
||||
expect(onceReturn).toBe(wrappedCursor);
|
||||
realCursor.emit('close');
|
||||
realCursor.emit('close');
|
||||
expect(closeEvents).toBe(2);
|
||||
expect(onceEvents).toBe(1);
|
||||
|
||||
// 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<PropertyKey, unknown>;
|
||||
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;
|
||||
const destroyStream = wrappedCursor.stream();
|
||||
destroyStream.destroy();
|
||||
await new Promise(resolve => setImmediate(resolve));
|
||||
expect(closeMock).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test('passes through safe read operations on client and proxies', async () => {
|
||||
const { client, dbStub, collectionStub } = createStubbedClient(true);
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue