195 lines
5.7 KiB
TypeScript
195 lines
5.7 KiB
TypeScript
import mongoose from 'mongoose';
|
|
import { recordMongooseQueryPerformance } from './performance-observer';
|
|
|
|
const QUERY_PERFORMANCE_START = Symbol('queryPerformanceStart');
|
|
const QUERY_PERFORMANCE_RECORDED = Symbol('queryPerformanceRecorded');
|
|
const PERFORMANCE_PLUGIN_APPLIED = Symbol('performancePluginApplied');
|
|
|
|
const QUERY_OPERATIONS = [
|
|
'countDocuments',
|
|
'deleteMany',
|
|
'deleteOne',
|
|
'find',
|
|
'findOne',
|
|
'findOneAndDelete',
|
|
'findOneAndReplace',
|
|
'findOneAndUpdate',
|
|
'replaceOne',
|
|
'updateMany',
|
|
'updateOne',
|
|
] as const;
|
|
const QUERY_OPERATION_REGEX = new RegExp(`^(${QUERY_OPERATIONS.join('|')})$`);
|
|
|
|
type QueryWithPerformanceState = mongoose.Query<unknown, unknown> & {
|
|
[QUERY_PERFORMANCE_START]?: bigint;
|
|
[QUERY_PERFORMANCE_RECORDED]?: boolean;
|
|
};
|
|
|
|
type AggregateWithPerformanceState = mongoose.Aggregate<unknown[]> & {
|
|
[QUERY_PERFORMANCE_START]?: bigint;
|
|
[QUERY_PERFORMANCE_RECORDED]?: boolean;
|
|
};
|
|
|
|
type SchemaWithPerformanceMarker = mongoose.Schema & {
|
|
[PERFORMANCE_PLUGIN_APPLIED]?: boolean;
|
|
};
|
|
|
|
export function applyMongoosePerformancePlugin(schemaValue: unknown): void {
|
|
if (!(schemaValue instanceof mongoose.Schema)) {
|
|
throw new TypeError('Mongoose performance plugin requires a Schema.');
|
|
}
|
|
const schema = schemaValue as SchemaWithPerformanceMarker;
|
|
if (schema[PERFORMANCE_PLUGIN_APPLIED]) return;
|
|
schema[PERFORMANCE_PLUGIN_APPLIED] = true;
|
|
|
|
schema.pre(QUERY_OPERATION_REGEX, function () {
|
|
const query = this as QueryWithPerformanceState;
|
|
query[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
|
|
query[QUERY_PERFORMANCE_RECORDED] = false;
|
|
});
|
|
|
|
schema.post(QUERY_OPERATION_REGEX, function (result: unknown) {
|
|
recordQueryPerformance(this as QueryWithPerformanceState, result);
|
|
});
|
|
|
|
schema.post(
|
|
QUERY_OPERATION_REGEX,
|
|
{ errorHandler: true },
|
|
function (
|
|
error: Error,
|
|
_result: unknown,
|
|
next: (error?: mongoose.CallbackError) => void,
|
|
) {
|
|
recordQueryPerformance(
|
|
this as unknown as QueryWithPerformanceState,
|
|
undefined,
|
|
error,
|
|
);
|
|
next(error);
|
|
},
|
|
);
|
|
|
|
schema.pre('aggregate', function () {
|
|
const aggregate = this as AggregateWithPerformanceState;
|
|
aggregate[QUERY_PERFORMANCE_START] = process.hrtime.bigint();
|
|
aggregate[QUERY_PERFORMANCE_RECORDED] = false;
|
|
});
|
|
|
|
schema.post('aggregate', function (result: unknown) {
|
|
recordAggregatePerformance(this as AggregateWithPerformanceState, result);
|
|
});
|
|
|
|
schema.post(
|
|
'aggregate',
|
|
{ errorHandler: true },
|
|
function (
|
|
error: Error,
|
|
_result: unknown,
|
|
next: (error?: mongoose.CallbackError) => void,
|
|
) {
|
|
recordAggregatePerformance(
|
|
this as AggregateWithPerformanceState,
|
|
undefined,
|
|
error,
|
|
);
|
|
next(error);
|
|
},
|
|
);
|
|
}
|
|
|
|
function recordQueryPerformance(
|
|
query: QueryWithPerformanceState,
|
|
result: unknown,
|
|
error?: unknown,
|
|
): void {
|
|
if (query[QUERY_PERFORMANCE_RECORDED]) return;
|
|
query[QUERY_PERFORMANCE_RECORDED] = true;
|
|
|
|
const startedAt = query[QUERY_PERFORMANCE_START];
|
|
if (!startedAt) return;
|
|
|
|
const hydratedDocsReturned = countHydratedDocuments(result);
|
|
const model = query.model as mongoose.Model<unknown> | undefined;
|
|
const options = query.getOptions();
|
|
|
|
recordMongooseQueryPerformance({
|
|
operation: (query as unknown as { op?: string }).op ?? 'query',
|
|
modelName: model?.modelName ?? 'unknown',
|
|
collectionName: model?.collection?.name,
|
|
durationMs: toDurationMs(startedAt),
|
|
docsReturned: countReturnedDocuments(result),
|
|
hydratedDocsReturned,
|
|
lean: Boolean(query.mongooseOptions().lean),
|
|
limit: numberOption(options.limit),
|
|
skip: numberOption(options.skip),
|
|
filterKeys: joinObjectKeys(query.getFilter()),
|
|
projectionKeys: joinObjectKeys(query.projection()),
|
|
sortKeys: joinObjectKeys(options.sort),
|
|
errorName: errorName(error),
|
|
});
|
|
}
|
|
|
|
function recordAggregatePerformance(
|
|
aggregate: AggregateWithPerformanceState,
|
|
result: unknown,
|
|
error?: unknown,
|
|
): void {
|
|
if (aggregate[QUERY_PERFORMANCE_RECORDED]) return;
|
|
aggregate[QUERY_PERFORMANCE_RECORDED] = true;
|
|
|
|
const startedAt = aggregate[QUERY_PERFORMANCE_START];
|
|
if (!startedAt) return;
|
|
|
|
const model = aggregate.model();
|
|
recordMongooseQueryPerformance({
|
|
operation: 'aggregate',
|
|
modelName: model?.modelName ?? 'unknown',
|
|
collectionName: model?.collection?.name,
|
|
durationMs: toDurationMs(startedAt),
|
|
docsReturned: countReturnedDocuments(result),
|
|
hydratedDocsReturned: countHydratedDocuments(result),
|
|
lean: true,
|
|
errorName: errorName(error),
|
|
});
|
|
}
|
|
|
|
export function countReturnedDocuments(result: unknown): number {
|
|
if (Array.isArray(result)) return result.length;
|
|
if (result == null) return 0;
|
|
if (typeof result === 'number') return result;
|
|
return 1;
|
|
}
|
|
|
|
export function countHydratedDocuments(result: unknown): number {
|
|
if (Array.isArray(result)) {
|
|
return result.filter((item) => isHydratedDocument(item)).length;
|
|
}
|
|
return isHydratedDocument(result) ? 1 : 0;
|
|
}
|
|
|
|
function isHydratedDocument(value: unknown): boolean {
|
|
return Boolean(
|
|
value &&
|
|
typeof value === 'object' &&
|
|
'$__' in (value as Record<string, unknown>),
|
|
);
|
|
}
|
|
|
|
function toDurationMs(startedAt: bigint): number {
|
|
return Number(process.hrtime.bigint() - startedAt) / 1_000_000;
|
|
}
|
|
|
|
function numberOption(value: unknown): number | undefined {
|
|
return typeof value === 'number' ? value : undefined;
|
|
}
|
|
|
|
function joinObjectKeys(value: unknown): string | undefined {
|
|
if (!value || typeof value !== 'object') return undefined;
|
|
const keys = Object.keys(value as Record<string, unknown>).sort();
|
|
return keys.length > 0 ? keys.join(',') : undefined;
|
|
}
|
|
|
|
function errorName(error: unknown): string | undefined {
|
|
return error instanceof Error ? error.name : undefined;
|
|
}
|