Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
14 changes: 12 additions & 2 deletions plugins/node/instrumentation-mongoose/src/mongoose.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,9 +107,14 @@ export class MongooseInstrumentation extends InstrumentationBase<MongooseInstrum
}

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

this._wrap(
moduleExports.Model.prototype,
'save',
Expand Down Expand Up @@ -155,9 +160,14 @@ export class MongooseInstrumentation extends InstrumentationBase<MongooseInstrum
}

private unpatch(
moduleExports: typeof mongoose,
module: any,
moduleVersion: string | undefined
): void {
const moduleExports: typeof mongoose =
module[Symbol.toStringTag] === 'Module'
? module.default // ESM
: 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 All @@ -35,6 +37,8 @@ import * as mongoose from 'mongoose';
import User, { IUser, loadUsers } from './user';
import { assertSpan, getStatement } from './asserts';
import { DB_NAME, MONGO_URI } from './config';
import * as testUtils from "@opentelemetry/contrib-test-utils";
import assert from "assert";

// Please run mongodb in the background: docker run -d -p 27017:27017 -v ~/data:/data/db mongo
describe('mongoose instrumentation [common]', () => {
Expand Down Expand Up @@ -548,4 +552,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);
},
});
});
});
Loading