Skip to content

fix: instrumentation of ESM-imported mongoose #2793

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 4 commits into from
Apr 30, 2025
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
20 changes: 12 additions & 8 deletions plugins/node/instrumentation-mongoose/src/mongoose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,10 +106,12 @@
return module;
}

private patch(
moduleExports: typeof mongoose,
moduleVersion: string | undefined
) {
private patch(module: any, moduleVersion: string | undefined) {
const moduleExports: typeof mongoose =
module[Symbol.toStringTag] === 'Module'
? module.default // ESM

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L112 was not covered by tests
: module; // CommonJS

this._wrap(
moduleExports.Model.prototype,
'save',
Expand Down Expand Up @@ -154,10 +156,12 @@
return moduleExports;
}

private unpatch(
moduleExports: typeof mongoose,
moduleVersion: string | undefined
): void {
private unpatch(module: any, moduleVersion: string | undefined): void {
const moduleExports: typeof mongoose =
module[Symbol.toStringTag] === 'Module'
? module.default // ESM

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

View check run for this annotation

Codecov / codecov/patch

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

Added line #L162 was not covered by tests
: module; // CommonJS

const contextCaptureFunctions = getContextCaptureFunctions(moduleVersion);

this._unwrap(moduleExports.Model.prototype, 'save');
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
/*
* Copyright The OpenTelemetry Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

// Use mongoose from an ES module:
// node --experimental-loader=@opentelemetry/instrumentation/hook.mjs use-mongoose.mjs [MONGO_URL] [DB_NAME

import { trace } from '@opentelemetry/api';
import { createTestNodeSdk } from '@opentelemetry/contrib-test-utils';

import { MongooseInstrumentation } from '../../build/src/index.js';

const sdk = createTestNodeSdk({
serviceName: 'use-mongoose',
instrumentations: [new MongooseInstrumentation()],
});
sdk.start();

import assert from 'assert';
import mongoose from 'mongoose';

const MONGO_URL = process.argv[2] || '';
const DB_NAME = process.argv[3] || '';

const randomId = ((Math.random() * 2 ** 32) >>> 0).toString(16);

await mongoose.connect(MONGO_URL, {
dbName: DB_NAME,
});

const TestModel = mongoose.model(
'Test',
new mongoose.Schema({
name: String,
})
);

const tracer = trace.getTracer('mongoose-instrumentation');
await tracer.startActiveSpan('manual', async span => {
const name = `test-${randomId}`;
const [createdDoc] = await TestModel.create([{ name }]);

const doc = await TestModel.findOne({ name }).exec();

assert(doc && createdDoc?._id.toString() === doc?._id.toString());

span.end();
});

await mongoose.disconnect();
await sdk.shutdown();
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,10 @@
* limitations under the License.
*/
import 'mocha';
import * as assert from 'assert';
import { expect } from 'expect';
import { context, ROOT_CONTEXT } from '@opentelemetry/api';
import * as testUtils from '@opentelemetry/contrib-test-utils';
import {
SEMATTRS_DB_OPERATION,
SEMATTRS_DB_STATEMENT,
Expand Down Expand Up @@ -548,4 +550,27 @@ describe('mongoose instrumentation [common]', () => {
expect(spans.length).toBe(0);
});
});

it('should work with ESM usage', async () => {
await testUtils.runTestFixture({
cwd: __dirname,
argv: ['fixtures/use-mongoose.mjs', MONGO_URI, DB_NAME],
env: {
NODE_OPTIONS:
'--experimental-loader=@opentelemetry/instrumentation/hook.mjs',
NODE_NO_WARNINGS: '1',
},
checkResult: (err, stdout, stderr) => {
assert.ifError(err);
},
checkCollector: (collector: testUtils.TestCollector) => {
const spans = collector.sortedSpans;
assert.strictEqual(spans[0].name, 'manual');
assert.strictEqual(spans[1].name, 'mongoose.Test.save');
assert.strictEqual(spans[1].parentSpanId, spans[0].spanId);
assert.strictEqual(spans[2].name, 'mongoose.Test.findOne');
assert.strictEqual(spans[2].parentSpanId, spans[0].spanId);
},
});
});
});