stock-bot/libs/data/mongodb/src/client.ts

1251 lines
39 KiB
TypeScript

import { Readable } from 'node:stream';
import type {
AggregateOptions,
AggregationCursor,
BulkWriteOptions,
CountDocumentsOptions,
CreateCollectionOptions,
CreateIndexesOptions,
DeleteOptions,
Document,
DropIndexesOptions,
Filter,
FindOptions,
IndexSpecification,
OptionalUnlessRequiredId,
UpdateOptions,
} from 'mongodb';
import { Collection, Db, MongoClient } from 'mongodb';
import type { Logger } from '@stock-bot/logger';
import type {
ConnectionEvents,
DocumentBase,
MongoDBClientConfig,
PoolMetrics,
} from './types';
const READ_ONLY_CURSOR_FLUENT_MODIFIERS = [
'filter',
'hint',
'min',
'max',
'returnKey',
'showRecordId',
'addQueryModifier',
'comment',
'maxAwaitTimeMS',
'maxTimeMS',
'project',
'sort',
'allowDiskUse',
'collation',
'limit',
'skip',
'batchSize',
'withReadPreference',
'withReadConcern',
'addCursorFlag',
] as const;
const READ_ONLY_COLLECTION_METHODS = new Set<string | symbol>([
'find',
'findOne',
'countDocuments',
'estimatedDocumentCount',
'distinct',
'listIndexes',
'indexExists',
'indexes',
'options',
]);
const READ_ONLY_COLLECTION_PROPS = new Set<string | symbol>([
'collectionName',
'dbName',
'namespace',
'then',
]);
const READ_ONLY_DB_METHODS = new Set<string | symbol>(['listCollections', 'stats']);
const READ_ONLY_DB_PROPS = new Set<string | symbol>([
'databaseName',
'namespace',
'options',
'then',
]);
export class MongoDBClient {
private client: MongoClient | null = null;
private db: Db | null = null;
private readonly config: MongoDBClientConfig;
private defaultDatabase: string;
private readonly logger: Logger;
private isConnected = false;
private readonly metrics: PoolMetrics;
private readonly events?: ConnectionEvents;
constructor(mongoConfig: MongoDBClientConfig, logger: Logger, events?: ConnectionEvents) {
this.config = mongoConfig;
this.defaultDatabase = mongoConfig.database || 'stock';
this.logger = logger;
this.events = events;
this.metrics = {
totalConnections: 0,
activeConnections: 0,
idleConnections: 0,
waitingRequests: 0,
errors: 0,
created: new Date(),
};
}
async connect(retryAttempts: number = 3, retryDelay: number = 1000): Promise<void> {
if (this.isConnected && this.client) {
return;
}
let lastError: Error | null = null;
for (let attempt = 1; attempt <= retryAttempts; attempt++) {
try {
const uri = this.buildConnectionUri();
this.logger.info(`Connecting to MongoDB (attempt ${attempt}/${retryAttempts})...`);
this.client = new MongoClient(uri, {
maxPoolSize: this.config.poolSettings?.maxPoolSize || 10,
minPoolSize: this.config.poolSettings?.minPoolSize || 1,
maxIdleTimeMS: this.config.poolSettings?.maxIdleTime,
connectTimeoutMS: this.config.timeouts?.connectTimeout || 10000,
socketTimeoutMS: this.config.timeouts?.socketTimeout || 30000,
serverSelectionTimeoutMS: this.config.timeouts?.serverSelectionTimeout || 5000,
});
await this.client.connect();
await this.client.db(this.defaultDatabase).command({ ping: 1 });
this.db = this.client.db(this.defaultDatabase);
this.isConnected = true;
this.metrics.totalConnections = this.config.poolSettings?.maxPoolSize || 10;
this.metrics.idleConnections = this.metrics.totalConnections;
if (this.events?.onConnect) {
await Promise.resolve(this.events.onConnect());
}
if (this.events?.onPoolCreated) {
await Promise.resolve(this.events.onPoolCreated());
}
this.logger.info('Successfully connected to MongoDB', {
database: this.defaultDatabase,
poolSize: this.metrics.totalConnections,
readOnly: Boolean(this.config.readOnly),
});
return;
} catch (error) {
lastError = error as Error;
this.metrics.errors++;
this.metrics.lastError = lastError.message;
if (this.events?.onError) {
await Promise.resolve(this.events.onError(lastError));
}
this.logger.error(`MongoDB connection attempt ${attempt} failed:`, error);
if (this.client) {
await this.client.close().catch(() => {});
this.client = null;
}
if (attempt < retryAttempts) {
await new Promise(resolve => setTimeout(resolve, retryDelay * attempt));
}
}
}
throw new Error(
`Failed to connect to MongoDB after ${retryAttempts} attempts: ${lastError?.message}`
);
}
async disconnect(): Promise<void> {
if (!this.client) {
return;
}
try {
await this.client.close();
this.isConnected = false;
this.client = null;
this.db = null;
if (this.events?.onDisconnect) {
await Promise.resolve(this.events.onDisconnect());
}
this.logger.info('Disconnected from MongoDB');
} catch (error) {
this.logger.error('Error disconnecting from MongoDB:', error);
throw error;
}
}
setDefaultDatabase(databaseName: string): void {
this.defaultDatabase = databaseName;
if (this.client) {
this.db = this.client.db(databaseName);
this.logger.debug(`Default database changed to: ${databaseName}`);
}
}
getDefaultDatabase(): string {
return this.defaultDatabase;
}
private getRawDatabase(databaseName?: string): Db {
if (!this.client) {
throw new Error('MongoDB client not connected');
}
return this.client.db(databaseName || this.defaultDatabase);
}
private createGuardedCursorStream(
cursor: {
next: () => Promise<unknown>;
close?: () => Promise<unknown>;
},
options?: { transform?: (doc: never) => unknown },
beforeRead?: () => void
): Readable {
beforeRead?.();
const transform = options?.transform;
let closePromise: Promise<unknown> | null = null;
const closeCursor = (): Promise<unknown> => {
if (!closePromise) {
closePromise = typeof cursor.close === 'function' ? cursor.close() : Promise.resolve();
}
return closePromise;
};
let readInProgress = false;
return new Readable({
objectMode: true,
autoDestroy: false,
highWaterMark: 1,
read() {
if (readInProgress) {
return;
}
readInProgress = true;
const readNext = (): void => {
try {
beforeRead?.();
} catch (err) {
readInProgress = false;
this.destroy(err instanceof Error ? err : new Error(String(err)));
return;
}
cursor.next().then(
doc => {
if (doc === null || doc === undefined) {
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 || output === undefined) {
readNext();
return;
}
}
if (this.push(output)) {
readNext();
} else {
readInProgress = false;
}
},
err => {
readInProgress = false;
this.destroy(err instanceof Error ? err : new Error(String(err)));
}
);
};
readNext();
},
destroy(error, callback) {
closeCursor().then(
() => callback(error),
closeError =>
callback(closeError instanceof Error ? closeError : new Error(String(closeError)))
);
},
});
}
private createTrackedCursorEventMethods(
cursor: Record<PropertyKey, unknown>,
wrapped: Record<PropertyKey, unknown>
): Record<string, unknown> {
type CursorListener = (...args: unknown[]) => void;
interface TrackedListener {
original: CursorListener;
bound: CursorListener;
once: boolean;
}
const trackedListeners = new Map<string | symbol, TrackedListener[]>();
const invokeCursorEventMethod = (method: string, ...args: unknown[]): unknown => {
const fn = cursor[method];
return typeof fn === 'function' ? fn.apply(cursor, args) : undefined;
};
const detachFromCursor = (event: string | symbol, bound: CursorListener): void => {
if (typeof cursor.removeListener === 'function') {
invokeCursorEventMethod('removeListener', event, bound);
} else if (typeof cursor.off === 'function') {
invokeCursorEventMethod('off', event, bound);
}
};
const removeTrackedEntry = (event: string | symbol, entry: TrackedListener): void => {
const entries = trackedListeners.get(event);
if (!entries) {
return;
}
const index = entries.indexOf(entry);
if (index !== -1) {
entries.splice(index, 1);
}
if (entries.length === 0) {
trackedListeners.delete(event);
}
};
const registerTrackedListener = (
event: string | symbol,
listener: CursorListener,
options: { once: boolean; prepend: boolean }
) => {
const entry: TrackedListener = {
original: listener,
once: options.once,
bound: (...args: unknown[]) => {
if (entry.once) {
removeTrackedEntry(event, entry);
}
listener.apply(wrapped, args);
},
};
const entries = trackedListeners.get(event) ?? [];
if (options.prepend) {
entries.unshift(entry);
} else {
entries.push(entry);
}
trackedListeners.set(event, entries);
if (options.prepend) {
if (options.once) {
invokeCursorEventMethod('prependOnceListener', event, entry.bound);
} else {
invokeCursorEventMethod('prependListener', event, entry.bound);
}
} else if (options.once) {
invokeCursorEventMethod('once', event, entry.bound);
} else {
invokeCursorEventMethod('on', event, entry.bound);
}
return wrapped;
};
const unregisterTrackedListener = (event: string | symbol, listener: CursorListener) => {
const entries = trackedListeners.get(event);
if (!entries) {
return wrapped;
}
let index = -1;
for (let i = entries.length - 1; i >= 0; i--) {
if (entries[i]?.original === listener) {
index = i;
break;
}
}
if (index !== -1) {
const [removed] = entries.splice(index, 1);
if (entries.length === 0) {
trackedListeners.delete(event);
}
if (removed) {
detachFromCursor(event, removed.bound);
}
}
return wrapped;
};
return {
on: (event: string | symbol, listener: CursorListener) =>
registerTrackedListener(event, listener, { once: false, prepend: false }),
once: (event: string | symbol, listener: CursorListener) =>
registerTrackedListener(event, listener, { once: true, prepend: false }),
off: (event: string | symbol, listener: CursorListener) =>
unregisterTrackedListener(event, listener),
addListener: (event: string | symbol, listener: CursorListener) =>
registerTrackedListener(event, listener, { once: false, prepend: false }),
removeListener: (event: string | symbol, listener: CursorListener) =>
unregisterTrackedListener(event, listener),
removeAllListeners: (event?: string | symbol) => {
if (event !== undefined) {
const entries = trackedListeners.get(event);
if (entries) {
for (const entry of entries) {
detachFromCursor(event, entry.bound);
}
trackedListeners.delete(event);
}
} else {
for (const [ev, entries] of trackedListeners) {
for (const entry of entries) {
detachFromCursor(ev, entry.bound);
}
}
trackedListeners.clear();
}
return wrapped;
},
prependListener: (event: string | symbol, listener: CursorListener) =>
registerTrackedListener(event, listener, { once: false, prepend: true }),
prependOnceListener: (event: string | symbol, listener: CursorListener) =>
registerTrackedListener(event, listener, { once: true, prepend: true }),
setMaxListeners: (n: number) => {
invokeCursorEventMethod('setMaxListeners', n);
return wrapped;
},
getMaxListeners: () =>
typeof cursor.getMaxListeners === 'function'
? (invokeCursorEventMethod('getMaxListeners') as number)
: 10,
listeners: (event: string | symbol) =>
(trackedListeners.get(event) ?? []).map(entry => entry.original),
rawListeners: (event: string | symbol) =>
(trackedListeners.get(event) ?? []).map(entry => entry.original),
listenerCount: (event: string | symbol) => trackedListeners.get(event)?.length ?? 0,
eventNames: () => Array.from(trackedListeners.keys()),
};
}
private wrapReadOnlyCursor<TCursor extends object>(cursor: TCursor): TCursor {
const rawCursor = cursor as Record<PropertyKey, unknown>;
const delegate = (method: string) => (...args: unknown[]) => {
const fn = rawCursor[method];
if (typeof fn !== 'function') {
throw new TypeError(`Cursor does not implement "${method}"`);
}
return fn.apply(cursor, args);
};
const wrapped: Record<PropertyKey, unknown> = {
get id() {
return rawCursor.id;
},
get namespace() {
return rawCursor.namespace;
},
get readPreference() {
return rawCursor.readPreference;
},
get readConcern() {
return rawCursor.readConcern;
},
get closed() {
return rawCursor.closed;
},
get killed() {
return rawCursor.killed;
},
get loadBalanced() {
return rawCursor.loadBalanced;
},
toArray: delegate('toArray'),
next: delegate('next'),
tryNext: delegate('tryNext'),
hasNext: delegate('hasNext'),
forEach: (iterator: (doc: unknown) => boolean | void) => {
const fn = rawCursor.forEach;
if (typeof fn !== 'function') {
throw new TypeError('Cursor does not implement "forEach"');
}
if (typeof iterator !== 'function') {
return fn.call(cursor, iterator);
}
return fn.call(cursor, (doc: unknown) => iterator.call(wrapped, doc));
},
count: delegate('count'),
explain: delegate('explain'),
close: delegate('close'),
rewind: delegate('rewind'),
bufferedCount: delegate('bufferedCount'),
readBufferedDocuments: delegate('readBufferedDocuments'),
stream: (options?: { transform?: (doc: never) => unknown }) =>
this.createGuardedCursorStream(
rawCursor as unknown as {
next: () => Promise<unknown>;
close?: () => Promise<unknown>;
},
options
),
[Symbol.asyncIterator]: () => {
const iterator = rawCursor[Symbol.asyncIterator];
if (typeof iterator !== 'function') {
throw new TypeError('Cursor is not async iterable');
}
return iterator.call(cursor);
},
[Symbol.asyncDispose]: () => {
const dispose = rawCursor[Symbol.asyncDispose];
if (typeof dispose === 'function') {
return dispose.call(cursor);
}
const close = rawCursor.close;
return typeof close === 'function' ? close.call(cursor) : Promise.resolve();
},
map: (transform: (doc: unknown) => unknown) => {
const fn = rawCursor.map;
if (typeof fn !== 'function') {
throw new TypeError('Cursor does not implement "map"');
}
const receiverRef: { current: unknown } = { current: undefined };
const guardedTransform =
typeof transform === 'function'
? (doc: unknown) => transform.call(receiverRef.current, doc)
: transform;
const mapped = fn.call(cursor, guardedTransform);
const result =
mapped === cursor
? wrapped
: mapped && typeof mapped === 'object'
? this.wrapReadOnlyCursor(mapped as object)
: mapped;
receiverRef.current = result;
return result;
},
clone: () => {
const fn = rawCursor.clone;
if (typeof fn !== 'function') {
throw new TypeError('Cursor does not implement "clone"');
}
const cloned = fn.call(cursor);
return cloned && typeof cloned === 'object'
? this.wrapReadOnlyCursor(cloned as object)
: cloned;
},
};
for (const modifier of READ_ONLY_CURSOR_FLUENT_MODIFIERS) {
if (typeof rawCursor[modifier] === 'function') {
wrapped[modifier] = (...args: unknown[]) => {
const fn = rawCursor[modifier] as (...modifierArgs: unknown[]) => unknown;
const result = fn.apply(cursor, args);
if (result === cursor) {
return wrapped;
}
if (result && typeof result === 'object') {
return this.wrapReadOnlyCursor(result as object);
}
return result;
};
}
}
Object.assign(wrapped, this.createTrackedCursorEventMethods(rawCursor, wrapped));
return wrapped as unknown as TCursor;
}
private wrapReadOnlyAggregationCursor<T extends Document>(
cursor: AggregationCursor<T>
): AggregationCursor<T> {
const assertCursorPipelineSafe = (): void => {
if (Array.isArray(cursor.pipeline)) {
this.assertReadOnlyPipeline(cursor.pipeline);
}
};
const wrapped: Record<PropertyKey, unknown> = {
get id() {
return cursor.id;
},
get namespace() {
return cursor.namespace;
},
get readPreference() {
return cursor.readPreference;
},
get readConcern() {
return cursor.readConcern;
},
get closed() {
return cursor.closed;
},
get killed() {
return cursor.killed;
},
get loadBalanced() {
return cursor.loadBalanced;
},
get pipeline() {
return Object.freeze(Array.isArray(cursor.pipeline) ? [...cursor.pipeline] : []);
},
// Read / iteration operations
toArray: () => {
assertCursorPipelineSafe();
return cursor.toArray();
},
next: () => {
assertCursorPipelineSafe();
return cursor.next();
},
tryNext: () => {
assertCursorPipelineSafe();
return cursor.tryNext();
},
hasNext: () => {
assertCursorPipelineSafe();
return cursor.hasNext();
},
forEach: (iterator: (doc: T) => boolean | void) => {
assertCursorPipelineSafe();
if (typeof iterator !== 'function') {
return cursor.forEach(iterator);
}
return cursor.forEach(doc => iterator.call(wrapped, doc));
},
stream: (options?: Parameters<AggregationCursor<T>['stream']>[0]) =>
this.createGuardedCursorStream(
cursor as unknown as {
next: () => Promise<unknown>;
close?: () => Promise<unknown>;
},
options as { transform?: (doc: never) => unknown } | undefined,
assertCursorPipelineSafe
) as ReturnType<AggregationCursor<T>['stream']>,
explain: (...args: Parameters<AggregationCursor<T>['explain']>) => {
assertCursorPipelineSafe();
return cursor.explain(...args);
},
close: (...args: Parameters<AggregationCursor<T>['close']>) => cursor.close(...args),
rewind: () => cursor.rewind(),
bufferedCount: () => cursor.bufferedCount(),
readBufferedDocuments: (count?: number) => cursor.readBufferedDocuments(count),
[Symbol.asyncIterator]: () => {
assertCursorPipelineSafe();
return cursor[Symbol.asyncIterator]();
},
[Symbol.asyncDispose]: () => {
const disposable = cursor as unknown as Partial<Record<symbol, () => Promise<void>>>;
const dispose = disposable[Symbol.asyncDispose];
return typeof dispose === 'function' ? dispose.call(cursor) : cursor.close();
},
// Fluent stage builders (read-only stages validated and wrapped)
out: () => {
throw new Error(
'MongoDB client is configured in read-only mode; aggregation cursor operation "out" is forbidden'
);
},
addStage: (stage: Document) => {
this.assertReadOnlyPipeline([stage]);
cursor.addStage(stage);
return wrapped;
},
lookup: ($lookup: Document) => {
this.assertReadOnlyPipeline([{ $lookup }]);
cursor.lookup($lookup);
return wrapped;
},
match: ($match: Document) => {
cursor.match($match);
return wrapped;
},
project: ($project: Document) => {
cursor.project($project);
return wrapped;
},
group: ($group: Document) => {
cursor.group($group);
return wrapped;
},
sort: ($sort: Parameters<AggregationCursor<T>['sort']>[0]) => {
cursor.sort($sort);
return wrapped;
},
limit: ($limit: number) => {
cursor.limit($limit);
return wrapped;
},
skip: ($skip: number) => {
cursor.skip($skip);
return wrapped;
},
unwind: ($unwind: Document | string) => {
cursor.unwind($unwind);
return wrapped;
},
redact: ($redact: Document) => {
cursor.redact($redact);
return wrapped;
},
geoNear: ($geoNear: Document) => {
cursor.geoNear($geoNear);
return wrapped;
},
// Fluent cursor modifiers
batchSize: (value: number) => {
cursor.batchSize(value);
return wrapped;
},
maxTimeMS: (value: number) => {
cursor.maxTimeMS(value);
return wrapped;
},
withReadPreference: (value: Parameters<AggregationCursor<T>['withReadPreference']>[0]) => {
cursor.withReadPreference(value);
return wrapped;
},
withReadConcern: (value: Parameters<AggregationCursor<T>['withReadConcern']>[0]) => {
cursor.withReadConcern(value);
return wrapped;
},
addCursorFlag: (
flag: Parameters<AggregationCursor<T>['addCursorFlag']>[0],
value: boolean
) => {
cursor.addCursorFlag(flag, value);
return wrapped;
},
map: <TMapped>(transform: (doc: T) => TMapped) => {
const receiverRef: { current: unknown } = { current: undefined };
const guardedTransform =
typeof transform === 'function'
? (doc: T) => transform.call(receiverRef.current, doc)
: transform;
const mapped = cursor.map(guardedTransform);
const result =
mapped === (cursor as unknown)
? wrapped
: this.wrapReadOnlyAggregationCursor(mapped as unknown as AggregationCursor<Document>);
receiverRef.current = result;
return result;
},
clone: () => this.wrapReadOnlyAggregationCursor(cursor.clone()),
};
Object.assign(
wrapped,
this.createTrackedCursorEventMethods(cursor as unknown as Record<PropertyKey, unknown>, wrapped)
);
return wrapped as unknown as AggregationCursor<T>;
}
private wrapReadOnlyCollection<T extends Document>(collection: Collection<T>): Collection<T> {
return new Proxy({} as Collection<T>, {
get: (_target, prop) => {
if (typeof prop === 'symbol' || READ_ONLY_COLLECTION_PROPS.has(prop)) {
return Reflect.get(collection, prop, collection);
}
if (prop === 'aggregate') {
return <TDoc extends Document = Document>(
pipeline: Document[] = [],
options?: AggregateOptions
) => {
const safePipeline = [...pipeline];
this.assertReadOnlyPipeline(safePipeline);
return this.wrapReadOnlyAggregationCursor(
collection.aggregate<TDoc>(safePipeline, options)
);
};
}
if (prop === 'find' || prop === 'listIndexes') {
const fn: unknown = Reflect.get(collection, prop, collection);
if (typeof fn === 'function') {
return (...args: unknown[]) => {
const cursor = (fn as (...methodArgs: unknown[]) => unknown).apply(collection, args);
return cursor && typeof cursor === 'object'
? this.wrapReadOnlyCursor(cursor as object)
: cursor;
};
}
return fn;
}
if (READ_ONLY_COLLECTION_METHODS.has(prop)) {
const fn = Reflect.get(collection, prop, collection);
return typeof fn === 'function' ? fn.bind(collection) : fn;
}
return () => {
throw new Error(
`MongoDB client is configured in read-only mode; collection operation "${String(prop)}" is forbidden`
);
};
},
});
}
private wrapReadOnlyDatabase(db: Db): Db {
return new Proxy({} as Db, {
get: (_target, prop) => {
if (typeof prop === 'symbol' || READ_ONLY_DB_PROPS.has(prop)) {
return Reflect.get(db, prop, db);
}
if (prop === 'collection') {
return <T extends Document = Document>(name: string) =>
this.wrapReadOnlyCollection(db.collection<T>(name));
}
if (prop === 'listCollections') {
const fn: unknown = Reflect.get(db, prop, db);
if (typeof fn === 'function') {
return (...args: unknown[]) => {
const cursor = (fn as (...methodArgs: unknown[]) => unknown).apply(db, args);
return cursor && typeof cursor === 'object'
? this.wrapReadOnlyCursor(cursor as object)
: cursor;
};
}
return fn;
}
if (READ_ONLY_DB_METHODS.has(prop)) {
const fn = Reflect.get(db, prop, db);
return typeof fn === 'function' ? fn.bind(db) : fn;
}
return () => {
throw new Error(
`MongoDB client is configured in read-only mode; database operation "${String(prop)}" is forbidden`
);
};
},
});
}
getDatabase(databaseName?: string): Db {
const raw = this.getRawDatabase(databaseName);
return this.config.readOnly ? this.wrapReadOnlyDatabase(raw) : raw;
}
getDb(dbName?: string): Db {
return this.getDatabase(dbName);
}
get database(): Db | null {
if (!this.db) {
return null;
}
return this.config.readOnly ? this.wrapReadOnlyDatabase(this.db) : this.db;
}
getCollection<T extends Document = Document>(name: string, database?: string): Collection<T> {
const raw = this.getRawDatabase(database).collection<T>(name);
return this.config.readOnly ? this.wrapReadOnlyCollection(raw) : raw;
}
collection<T extends Document = Document>(name: string, database?: string): Collection<T> {
return this.getCollection<T>(name, database);
}
isReadOnly(): boolean {
return this.config.readOnly === true;
}
private assertWritable(operation: string): void {
if (this.config.readOnly) {
throw new Error(
`MongoDB client is configured in read-only mode; write operation "${operation}" is forbidden`
);
}
}
private assertReadOnlyPipeline(pipeline: Document[]): void {
if (!this.config.readOnly) {
return;
}
const checkStage = (value: unknown): void => {
if (!value || typeof value !== 'object') {
return;
}
for (const [key, child] of Object.entries(value)) {
if (key === '$out' || key === '$merge') {
throw new Error(
`MongoDB client is configured in read-only mode; aggregation stage "${key}" is forbidden`
);
}
checkStage(child);
}
};
for (const stage of pipeline) {
checkStage(stage);
}
}
async batchUpsert<T extends DocumentBase>(
collectionName: string,
documents: Array<
Omit<T, '_id' | 'created_at' | 'updated_at'> & Partial<Pick<T, 'created_at' | 'updated_at'>>
>,
uniqueKeys: string | string[],
options: {
chunkSize?: number;
database?: string;
} = {}
): Promise<{ insertedCount: number; updatedCount: number; errors: unknown[] }> {
this.assertWritable(`batchUpsert(${collectionName})`);
if (!this.client) {
throw new Error('MongoDB client not connected');
}
if (documents.length === 0) {
return { insertedCount: 0, updatedCount: 0, errors: [] };
}
const keyFields = Array.isArray(uniqueKeys) ? uniqueKeys : [uniqueKeys];
if (keyFields.length === 0) {
throw new Error('At least one unique key must be provided');
}
const { chunkSize = 10000, database } = options;
const collection = this.getRawDatabase(database).collection<T>(collectionName);
const operationId = Math.random().toString(36).substring(7);
const dbName = database || this.defaultDatabase;
let totalInserted = 0;
let totalUpdated = 0;
for (let i = 0; i < documents.length; i += chunkSize) {
const chunk = documents.slice(i, i + chunkSize);
try {
const startTime = Date.now();
const bulkOps = chunk.map(doc => {
const now = new Date();
const docWithTimestamps = {
...doc,
created_at: doc.created_at || now,
updated_at: now,
};
const filter: Record<string, unknown> = {};
for (const key of keyFields) {
const value = (doc as Record<string, unknown>)[key];
if (value === undefined || value === null) {
throw new Error(`Document missing required unique key: ${key}`);
}
filter[key] = value;
}
const { created_at, ...updateFields } = docWithTimestamps;
return {
updateOne: {
filter,
update: {
$set: updateFields,
$setOnInsert: { created_at },
},
upsert: true,
},
};
});
const result = await collection.bulkWrite(bulkOps as never, { ordered: false });
totalInserted += result.upsertedCount;
totalUpdated += result.modifiedCount;
this.logger.debug(`Batch upsert chunk processed [${operationId}]`, {
chunkNumber: Math.floor(i / chunkSize) + 1,
chunkSize: chunk.length,
inserted: result.upsertedCount,
updated: result.modifiedCount,
executionTime: Date.now() - startTime,
database: dbName,
collection: collectionName,
});
} catch (error) {
this.logger.error(`Batch upsert failed on chunk [${operationId}]`, {
error,
database: dbName,
collection: collectionName,
chunkNumber: Math.floor(i / chunkSize) + 1,
chunkStart: i,
chunkSize: chunk.length,
uniqueKeys: keyFields,
});
throw error;
}
}
return { insertedCount: totalInserted, updatedCount: totalUpdated, errors: [] };
}
async insertOne<T extends DocumentBase>(
collectionName: string,
document: Omit<T, '_id' | 'created_at' | 'updated_at'> &
Partial<Pick<T, 'created_at' | 'updated_at'>>,
database?: string
): Promise<T> {
this.assertWritable(`insertOne(${collectionName})`);
const collection = this.getRawDatabase(database).collection<T>(collectionName);
const now = new Date();
const docWithTimestamps = {
...document,
created_at: document.created_at || now,
updated_at: now,
} as T;
const result = await collection.insertOne(docWithTimestamps as OptionalUnlessRequiredId<T>);
return { ...docWithTimestamps, _id: result.insertedId } as T;
}
async insertMany<T extends Document = Document>(
collectionName: string,
documents: T[],
options?: BulkWriteOptions,
dbName?: string
) {
this.assertWritable(`insertMany(${collectionName})`);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const now = new Date();
const docsWithTimestamps = documents.map(doc => ({
...doc,
created_at: doc.created_at || now,
updated_at: now,
}));
const result = await collection.insertMany(
docsWithTimestamps as OptionalUnlessRequiredId<Document>[],
options
);
return {
insertedCount: result.insertedCount,
insertedIds: result.insertedIds,
};
}
async find<T extends Document = Document>(
collectionName: string,
filter: Filter<Document> = {},
options?: FindOptions,
dbName?: string
): Promise<T[]> {
const collection = this.getCollection<T>(collectionName, dbName);
const cursor = collection.find(filter, options);
return (await cursor.toArray()) as T[];
}
async findOne<T extends Document = Document>(
collectionName: string,
filter: Filter<Document>,
options?: FindOptions,
dbName?: string
): Promise<T | null> {
const collection = this.getCollection<T>(collectionName, dbName);
const result = await collection.findOne(filter, options);
return result as T | null;
}
private withUpdatedTimestamp(update: Document): Document {
const now = new Date();
const hasOperator = Object.keys(update).some(key => key.startsWith('$'));
if (!hasOperator) {
return { $set: { ...update, updated_at: now } };
}
return {
...update,
$set: {
...(update.$set && typeof update.$set === 'object' ? update.$set : {}),
updated_at: now,
},
};
}
async updateOne(
collectionName: string,
filter: Filter<Document>,
update: Document,
options?: UpdateOptions,
dbName?: string
) {
this.assertWritable(`updateOne(${collectionName})`);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const result = await collection.updateOne(filter, this.withUpdatedTimestamp(update), options);
return {
matchedCount: result.matchedCount,
modifiedCount: result.modifiedCount,
upsertedCount: result.upsertedCount,
upsertedId: result.upsertedId,
};
}
async updateMany(
collectionName: string,
filter: Filter<Document>,
update: Document,
options?: UpdateOptions,
dbName?: string
) {
this.assertWritable(`updateMany(${collectionName})`);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const result = await collection.updateMany(filter, this.withUpdatedTimestamp(update), options);
return {
matchedCount: result.matchedCount,
modifiedCount: result.modifiedCount,
upsertedCount: result.upsertedCount,
upsertedId: result.upsertedId,
};
}
async deleteOne(
collectionName: string,
filter: Filter<Document>,
options?: DeleteOptions,
dbName?: string
) {
this.assertWritable(`deleteOne(${collectionName})`);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const result = await collection.deleteOne(filter, options);
return { deletedCount: result.deletedCount };
}
async deleteMany(
collectionName: string,
filter: Filter<Document>,
options?: DeleteOptions,
dbName?: string
) {
this.assertWritable(`deleteMany(${collectionName})`);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const result = await collection.deleteMany(filter, options);
return { deletedCount: result.deletedCount };
}
async countDocuments(
collectionName: string,
filter: Filter<Document> = {},
options?: CountDocumentsOptions,
dbName?: string
): Promise<number> {
const collection = this.getCollection(collectionName, dbName);
return await collection.countDocuments(filter, options);
}
async aggregate<T extends Document = Document>(
collectionName: string,
pipeline: Document[],
options?: AggregateOptions,
dbName?: string
): Promise<T[]> {
this.assertReadOnlyPipeline(pipeline);
const collection = this.getRawDatabase(dbName).collection(collectionName);
const cursor = collection.aggregate(pipeline, options);
return (await cursor.toArray()) as T[];
}
async createIndex(
collectionName: string,
indexSpec: IndexSpecification,
options?: CreateIndexesOptions,
dbName?: string
): Promise<string> {
this.assertWritable(`createIndex(${collectionName})`);
const collection = this.getRawDatabase(dbName).collection(collectionName);
return await collection.createIndex(indexSpec, options);
}
async dropIndex(
collectionName: string,
indexName: string,
options?: DropIndexesOptions,
dbName?: string
): Promise<void> {
this.assertWritable(`dropIndex(${collectionName})`);
const collection = this.getRawDatabase(dbName).collection(collectionName);
await collection.dropIndex(indexName, options);
}
async listIndexes(collectionName: string, dbName?: string): Promise<Document[]> {
const collection = this.getCollection(collectionName, dbName);
const cursor = collection.listIndexes();
return await cursor.toArray();
}
async createCollection(
collectionName: string,
options?: CreateCollectionOptions,
dbName?: string
): Promise<void> {
this.assertWritable(`createCollection(${collectionName})`);
const db = this.getRawDatabase(dbName);
await db.createCollection(collectionName, options);
}
async dropCollection(collectionName: string, dbName?: string): Promise<void> {
this.assertWritable(`dropCollection(${collectionName})`);
const db = this.getRawDatabase(dbName);
await db.dropCollection(collectionName);
}
async listCollections(filter: Filter<Document> = {}, dbName?: string): Promise<Document[]> {
const db = this.getDatabase(dbName);
return await db.listCollections(filter).toArray();
}
get connected(): boolean {
return this.isConnected && !!this.client;
}
getPoolMetrics(): PoolMetrics {
this.metrics.lastUsed = new Date();
return { ...this.metrics };
}
private buildConnectionUri(): string {
if (this.config.uri) {
return this.config.uri;
}
const { host, port, username, password, database, authSource } = this.config;
const auth =
username && password !== undefined
? `${encodeURIComponent(username)}:${encodeURIComponent(password)}@`
: '';
const authParam = authSource && username ? `?authSource=${encodeURIComponent(authSource)}` : '';
return `mongodb://${auth}${host}:${port}/${database}${authParam}`;
}
}