Skip to content

feat(instrumentation-mongoose): add instrumentation of static methods #2748

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 78 additions & 0 deletions plugins/node/instrumentation-mongoose/src/mongoose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,17 @@
});
this._wrap(moduleExports.Model, 'aggregate', this.patchModelAggregate());

this._wrap(
moduleExports.Model,
'insertMany',
this.patchModelStatic('insertMany', moduleVersion)
);
this._wrap(
moduleExports.Model,
'bulkWrite',
this.patchModelStatic('bulkWrite', moduleVersion)
);

return moduleExports;
}

Expand All @@ -179,6 +190,9 @@
this._unwrap(moduleExports.Query.prototype, funcName as any);
});
this._unwrap(moduleExports.Model, 'aggregate');

this._unwrap(moduleExports.Model, 'insertMany');
this._unwrap(moduleExports.Model, 'bulkWrite');
}

private patchAggregateExec(moduleVersion: string | undefined) {
Expand Down Expand Up @@ -314,6 +328,70 @@
};
}

private patchModelStatic(op: string, moduleVersion: string | undefined) {
const self = this;
return (original: Function) => {
return function patchedStatic(
this: any,
docsOrOps: any,
options?: any,
callback?: Function
) {
if (
self.getConfig().requireParentSpan &&
trace.getSpan(context.active()) === undefined

Check warning on line 342 in plugins/node/instrumentation-mongoose/src/mongoose.ts

View check run for this annotation

Codecov / codecov/patch

plugins/node/instrumentation-mongoose/src/mongoose.ts#L342

Added line #L342 was not covered by tests
) {
return original.apply(this, arguments);

Check warning on line 344 in plugins/node/instrumentation-mongoose/src/mongoose.ts

View check run for this annotation

Codecov / codecov/patch

plugins/node/instrumentation-mongoose/src/mongoose.ts#L344

Added line #L344 was not covered by tests
}
if (typeof options === 'function') {
callback = options;
options = undefined;
}

const serializePayload: SerializerPayload = {};
switch (op) {
case 'insertMany':
serializePayload.documents = docsOrOps;
break;
case 'bulkWrite':
serializePayload.operations = docsOrOps;
break;
default:
serializePayload.document = docsOrOps;
break;

Check warning on line 361 in plugins/node/instrumentation-mongoose/src/mongoose.ts

View check run for this annotation

Codecov / codecov/patch

plugins/node/instrumentation-mongoose/src/mongoose.ts#L359-L361

Added lines #L359 - L361 were not covered by tests
}
if (options !== undefined) {
serializePayload.options = options;
}

const attributes: Attributes = {};
const { dbStatementSerializer } = self.getConfig();
if (dbStatementSerializer) {
attributes[SEMATTRS_DB_STATEMENT] = dbStatementSerializer(
op,
serializePayload
);
}

const span = self._startSpan(
this.collection,
this.modelName,
op,
attributes
);

return self._handleResponse(
span,
original,
this,
arguments,
callback,
moduleVersion
);
};
};
}

// we want to capture the otel span on the object which is calling exec.
// in the special case of aggregate, we need have no function to path
// on the Aggregate object to capture the context on, so we patch
Expand Down
2 changes: 2 additions & 0 deletions plugins/node/instrumentation-mongoose/src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ export interface SerializerPayload {
document?: any;
aggregatePipeline?: any;
fields?: any;
documents?: any;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

(not for this PR): I guess the payload properties depend on the operation being serialized. This type and DbStatementSerializer could be improved by using a union on the type property and a specific type per opration in payload. This way we provide some hints to the devs who want to implement a serializer

Check this small example in TS playground.

operations?: any;
}

export type DbStatementSerializer = (
Expand Down
2 changes: 2 additions & 0 deletions plugins/node/instrumentation-mongoose/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ export function handleCallbackResponse(
let callbackArgumentIndex = 0;
if (args.length === 2) {
callbackArgumentIndex = 1;
} else if (args.length === 3) {
callbackArgumentIndex = 2;
}

args[callbackArgumentIndex] = (err: Error, response: any): any => {
Expand Down
104 changes: 102 additions & 2 deletions plugins/node/instrumentation-mongoose/test/mongoose-common.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,9 +74,8 @@ describe('mongoose instrumentation [common]', () => {
});
},
});
instrumentation.enable();
await loadUsers();
await User.createIndexes();
instrumentation.enable();
});

afterEach(async () => {
Expand Down Expand Up @@ -321,6 +320,107 @@ describe('mongoose instrumentation [common]', () => {
expect(statement.document).toEqual(expect.objectContaining(document));
});

it('instrumenting insertMany operation', async () => {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There is not test with options or callback params. Is it possible to ad one test for these cases?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added for insertMany.
This helped identify the issue with versions that I dropped support for.

const documents = [
{
firstName: 'John',
lastName: 'Doe',
email: 'john.doe+1@example.com',
},
{
firstName: 'Jane',
lastName: 'Doe',
email: 'jane.doe+1@example.com',
},
];
await User.insertMany(documents);

const spans = getTestSpans();
expect(spans.length).toBe(1);
assertSpan(spans[0] as ReadableSpan);
expect(spans[0].attributes[SEMATTRS_DB_OPERATION]).toBe('insertMany');
const statement = getStatement(spans[0] as ReadableSpan);
expect(statement.documents).toEqual(documents);
});

it('instrumenting bulkWrite operation', async () => {
const operations = [
{
insertOne: {
document: {
firstName: 'Jane',
lastName: 'Doe',
email: 'jane.doe+2@example.com',
age: 25,
},
},
},
{
updateMany: {
filter: { age: { $lte: 20 } },
update: { $set: { age: 20 } },
},
},
{
updateOne: {
filter: { firstName: 'Jane' },
update: { $inc: { age: 1 } },
},
},
{ deleteOne: { filter: { firstName: 'Michael' } } },
{
updateOne: {
filter: { firstName: 'Zara' },
update: {
$set: { lastName: 'Doe', age: 40, email: 'zara@example.com' },
},
upsert: true,
},
},
];
await User.bulkWrite(operations);

const spans = getTestSpans();
expect(spans.length).toBe(1);
assertSpan(spans[0] as ReadableSpan);
expect(spans[0].attributes[SEMATTRS_DB_OPERATION]).toBe('bulkWrite');
const statement = getStatement(spans[0] as ReadableSpan);
expect(statement.operations).toEqual([
{
insertOne: {
document: {
firstName: 'Jane',
lastName: 'Doe',
email: 'jane.doe+2@example.com',
age: 25,
},
},
},
{
updateMany: {
filter: { age: { $lte: 20 } },
update: { $set: { age: 20 } },
},
},
{
updateOne: {
filter: { firstName: 'Jane' },
update: { $inc: { age: 1 } },
},
},
{ deleteOne: { filter: { firstName: 'Michael' } } },
{
updateOne: {
filter: { firstName: 'Zara' },
update: {
$set: { lastName: 'Doe', age: 40, email: 'zara@example.com' },
},
upsert: true,
},
},
]);
});

it('instrumenting aggregate operation', async () => {
await User.aggregate([
{ $match: { firstName: 'John' } },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,8 @@ describe('mongoose instrumentation [v5/v6]', () => {
});
},
});
instrumentation.enable();
await loadUsers();
await User.createIndexes();
instrumentation.enable();
});

afterEach(async () => {
Expand Down Expand Up @@ -152,6 +151,61 @@ describe('mongoose instrumentation [v5/v6]', () => {
});
});

describe('when insertMany call has callback', async () => {
it('instrumenting insertMany operation with generic options and callback', done => {
const documents = [
{
firstName: 'John',
lastName: 'Doe',
email: 'john.doe+1@example.com',
},
{
firstName: 'Jane',
lastName: 'Doe',
email: 'jane.doe+1@example.com',
},
];
// @ts-ignore - v7 removed callback support
// https://mongoosejs.com/docs/migrating_to_7.html#dropped-callback-support
User.insertMany(documents, { ordered: true }, () => {
const spans = getTestSpans();
expect(spans.length).toBe(1);
assertSpan(spans[0] as ReadableSpan);
expect(spans[0].attributes[SEMATTRS_DB_OPERATION]).toBe('insertMany');
const statement = getStatement(spans[0] as ReadableSpan);
expect(statement.documents).toEqual(documents);
expect(statement.options.ordered).toEqual(true);
done();
});
});

it('instrumenting insertMany operation with only callback', done => {
const documents = [
{
firstName: 'John',
lastName: 'Doe',
email: 'john.doe+1@example.com',
},
{
firstName: 'Jane',
lastName: 'Doe',
email: 'jane.doe+1@example.com',
},
];
// @ts-ignore - v7 removed callback support
// https://mongoosejs.com/docs/migrating_to_7.html#dropped-callback-support
User.insertMany(documents, () => {
const spans = getTestSpans();
expect(spans.length).toBe(1);
assertSpan(spans[0] as ReadableSpan);
expect(spans[0].attributes[SEMATTRS_DB_OPERATION]).toBe('insertMany');
const statement = getStatement(spans[0] as ReadableSpan);
expect(statement.documents).toEqual(documents);
done();
});
});
});

describe('remove operation', () => {
it('instrumenting remove operation [deprecated]', async () => {
const user = await User.findOne({ email: 'john.doe@example.com' });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,8 @@ describe('mongoose instrumentation [v7/v8]', () => {
});
},
});
instrumentation.enable();
await loadUsers();
await User.createIndexes();
instrumentation.enable();
});

afterEach(async () => {
Expand Down