From c4efc68e8ec513230d38711b632bdbfe9b4fdc11 Mon Sep 17 00:00:00 2001 From: Guillaume Deconinck Date: Fri, 31 Mar 2023 23:31:28 +0900 Subject: [PATCH 01/14] feat(mongodb): add support for v5 --- .../.tav.yml | 4 +- .../package.json | 11 +- .../src/instrumentation.ts | 14 + .../test/mongodb-v3.test.ts | 2 +- .../test/mongodb-v4.test.ts | 2 +- .../test/mongodb-v5.test.ts | 556 ++++++++++++++++++ 6 files changed, 581 insertions(+), 8 deletions(-) create mode 100644 plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/.tav.yml b/plugins/node/opentelemetry-instrumentation-mongodb/.tav.yml index c369d133f6..4751a63619 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/.tav.yml +++ b/plugins/node/opentelemetry-instrumentation-mongodb/.tav.yml @@ -3,7 +3,9 @@ mongodb: - versions: ">=3.3 <4" commands: npm run test - versions: ">=4 <5" - commands: npm run test-new-versions + commands: npm run test-v4 + - versions: ">=5 <6" + commands: npm run test-v5 # Fix missing `contrib-test-utils` package pretest: npm run --prefix ../../../ lerna:link diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/package.json b/plugins/node/opentelemetry-instrumentation-mongodb/package.json index fc1526c84c..3bac20d841 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/package.json +++ b/plugins/node/opentelemetry-instrumentation-mongodb/package.json @@ -8,7 +8,8 @@ "scripts": { "docker:start": "docker run -e MONGODB_DB=opentelemetry-tests -e MONGODB_PORT=27017 -e MONGODB_HOST=127.0.0.1 -p 27017:27017 --rm mongo", "test": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v3.test.ts'", - "test-new-versions": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**mongodb-v4.test.ts'", + "test-v4": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v4.test.ts'", + "test-v5": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v5.test.ts'", "test-all-versions": "tav", "tdd": "npm run test -- --watch-extensions ts --watch", "clean": "rimraf build/*", @@ -51,16 +52,16 @@ }, "devDependencies": { "@opentelemetry/api": "^1.3.0", - "@opentelemetry/contrib-test-utils": "^0.33.2", "@opentelemetry/context-async-hooks": "^1.8.0", + "@opentelemetry/contrib-test-utils": "^0.33.2", "@opentelemetry/sdk-trace-base": "^1.8.0", "@opentelemetry/sdk-trace-node": "^1.8.0", + "@types/bson": "4.0.5", "@types/mocha": "7.0.2", + "@types/mongodb": "3.6.20", "@types/node": "18.11.7", "mocha": "7.2.0", "mongodb": "3.6.11", - "@types/mongodb": "3.6.20", - "@types/bson": "4.0.5", "nyc": "15.1.0", "rimraf": "4.2.0", "test-all-versions": "5.0.1", @@ -72,4 +73,4 @@ "@opentelemetry/semantic-conventions": "^1.0.0" }, "homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-mongodb#readme" -} +} \ No newline at end of file diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts index 8361de772c..6cb7c576cc 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts @@ -83,6 +83,20 @@ export class MongoDBInstrumentation extends InstrumentationBase { ), ] ), + new InstrumentationNodeModuleDefinition( + 'mongodb', + ['5.*'], + undefined, + undefined, + [ + new InstrumentationNodeModuleFile( + 'mongodb/lib/cmap/connection.js', + ['5.*'], + v4Patch, + v4Unpatch + ), + ] + ), ]; } diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v3.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v3.test.ts index 5a0b39e773..1337e91e8b 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v3.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v3.test.ts @@ -83,7 +83,7 @@ describe('MongoDBInstrumentation', () => { } // Non traced insertion of basic data to perform tests const insertData = [{ a: 1 }, { a: 2 }, { a: 3 }]; - collection.insertMany(insertData, (err, result) => { + collection.insertMany(insertData, (err: any, result: any) => { resetMemoryExporter(); done(); }); diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts index 3101a947d2..be2ed330d7 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts @@ -82,7 +82,7 @@ describe('MongoDBInstrumentation', () => { } // Non traced insertion of basic data to perform tests const insertData = [{ a: 1 }, { a: 2 }, { a: 3 }]; - collection.insertMany(insertData, (err, result) => { + collection.insertMany(insertData, (err: any, result: any) => { resetMemoryExporter(); done(); }); diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts new file mode 100644 index 0000000000..2b493ba3c4 --- /dev/null +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts @@ -0,0 +1,556 @@ +/* + * 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. + */ + +// for testing locally "npm run docker:start" + +import { context, trace, SpanKind, Span } from '@opentelemetry/api'; +import * as assert from 'assert'; +import { MongoDBInstrumentation, MongoDBInstrumentationConfig } from '../src'; +import { MongoResponseHookInformation } from '../src'; +import { + registerInstrumentationTesting, + getTestSpans, + resetMemoryExporter, +} from '@opentelemetry/contrib-test-utils'; + +const instrumentation = registerInstrumentationTesting( + new MongoDBInstrumentation() +); + +import * as mongodb from 'mongodb'; +import { assertSpans, accessCollection, DEFAULT_MONGO_HOST } from './utils'; +import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; + +describe('MongoDBInstrumentation', () => { + function create(config: MongoDBInstrumentationConfig = {}) { + instrumentation.setConfig(config); + } + // For these tests, mongo must be running. Add RUN_MONGODB_TESTS to run + // these tests. + const RUN_MONGODB_TESTS = process.env.RUN_MONGODB_TESTS as string; + let shouldTest = true; + if (!RUN_MONGODB_TESTS) { + console.log('Skipping test-mongodb. Run MongoDB to test'); + shouldTest = false; + } + + const URL = `mongodb://${process.env.MONGODB_HOST || DEFAULT_MONGO_HOST}:${ + process.env.MONGODB_PORT || '27017' + }`; + const DB_NAME = process.env.MONGODB_DB || 'opentelemetry-tests'; + const COLLECTION_NAME = 'test'; + + let client: mongodb.MongoClient; + let collection: mongodb.Collection; + + before(done => { + shouldTest = true; + accessCollection(URL, DB_NAME, COLLECTION_NAME) + .then(result => { + client = result.client; + collection = result.collection; + done(); + }) + .catch((err: Error) => { + console.log( + 'Skipping test-mongodb. Could not connect. Run MongoDB to test' + ); + shouldTest = false; + done(); + }); + }); + + beforeEach(async function mongoBeforeEach() { + // Skipping all tests in beforeEach() is a workaround. Mocha does not work + // properly when skipping tests in before() on nested describe() calls. + // https://github.com/mochajs/mocha/issues/2819 + if (!shouldTest) { + this.skip(); + } + // Non traced insertion of basic data to perform tests + const insertData = [{ a: 1 }, { a: 2 }, { a: 3 }]; + await collection.insertMany(insertData); + resetMemoryExporter(); + }); + + afterEach(async () => { + if (shouldTest) { + await collection.deleteMany({}); + } + }); + + after(() => { + if (client) { + client.close(); + } + }); + + /** Should intercept query */ + describe('Instrumenting query operations', () => { + it('should create a child span for insert', done => { + const insertData = [{ a: 1 }, { a: 2 }, { a: 3 }]; + const span = trace.getTracer('default').startSpan('insertRootSpan'); + context.with(trace.setSpan(context.active(), span), () => { + collection + .insertMany(insertData) + .then(() => { + span.end(); + assertSpans( + getTestSpans(), + 'mongodb.insert', + SpanKind.CLIENT, + 'insert' + ); + done(); + }) + .catch(err => { + done(err); + }); + }); + }); + + it('should create a child span for update', done => { + const span = trace.getTracer('default').startSpan('updateRootSpan'); + context.with(trace.setSpan(context.active(), span), () => { + collection + .updateOne({ a: 2 }, { $set: { b: 1 } }) + .then(() => { + span.end(); + assertSpans( + getTestSpans(), + 'mongodb.update', + SpanKind.CLIENT, + 'update' + ); + done(); + }) + .catch(err => { + done(err); + }); + }); + }); + + it('should create a child span for remove', done => { + const span = trace.getTracer('default').startSpan('removeRootSpan'); + context.with(trace.setSpan(context.active(), span), () => { + collection + .deleteOne({ a: 3 }) + .then(() => { + span.end(); + assertSpans( + getTestSpans(), + 'mongodb.delete', + SpanKind.CLIENT, + 'delete' + ); + done(); + }) + .catch(err => { + done(err); + }); + }); + }); + }); + + /** Should intercept cursor */ + describe('Instrumenting cursor operations', () => { + it('should create a child span for find', done => { + const span = trace.getTracer('default').startSpan('findRootSpan'); + context.with(trace.setSpan(context.active(), span), () => { + collection + .find({ a: 1 }) + .toArray() + .then(() => { + span.end(); + assertSpans( + getTestSpans(), + 'mongodb.find', + SpanKind.CLIENT, + 'find' + ); + done(); + }) + .catch(err => { + done(err); + }); + }); + }); + + it('should create a child span for cursor operations', done => { + const span = trace.getTracer('default').startSpan('findRootSpan'); + context.with(trace.setSpan(context.active(), span), () => { + const cursor = collection.find().batchSize(1); + cursor.next().then(firstElement => { + assert(firstElement !== null); + cursor + .next() + .then(secondElement => { + span.end(); + assert(secondElement !== null); + // assert that we correctly got the first as a find + assertSpans( + getTestSpans().filter( + span => !span.name.includes('mongodb.getMore') + ), + 'mongodb.find', + SpanKind.CLIENT, + 'find' + ); + // assert that we correctly got the first as a find + assertSpans( + getTestSpans().filter( + span => !span.name.includes('mongodb.find') + ), + 'mongodb.getMore', + SpanKind.CLIENT, + 'getMore' + ); + done(); + }) + .catch(err => { + done(err); + }); + }); + }); + }); + }); + + /** Should intercept command */ + describe('Instrumenting command operations', () => { + it('should create a child span for create index', done => { + const span = trace.getTracer('default').startSpan('indexRootSpan'); + context.with(trace.setSpan(context.active(), span), () => { + collection + .createIndex({ a: 1 }) + .then(() => { + span.end(); + assertSpans( + getTestSpans(), + 'mongodb.createIndexes', + SpanKind.CLIENT, + 'createIndexes' + ); + done(); + }) + .catch(err => { + done(err); + }); + }); + }); + }); + + describe('when using enhanced database reporting without db statementSerializer', () => { + const key = 'key'; + const value = 'value'; + const object = { [key]: value }; + + beforeEach(() => { + create({ + enhancedDatabaseReporting: false, + }); + }); + + it('should properly collect db statement (hide attribute values)', done => { + const span = trace.getTracer('default').startSpan('insertRootSpan'); + context.with(trace.setSpan(context.active(), span), () => { + collection + .insertOne(object) + .then(() => { + span.end(); + const spans = getTestSpans(); + const operationName = 'mongodb.insert'; + assertSpans( + spans, + operationName, + SpanKind.CLIENT, + 'insert', + false, + false + ); + const mongoSpan = spans.find(s => s.name === operationName); + const dbStatement = JSON.parse( + mongoSpan!.attributes[SemanticAttributes.DB_STATEMENT] as string + ); + assert.strictEqual(dbStatement[key], '?'); + done(); + }) + .catch(err => { + done(err); + }); + }); + }); + }); + + describe('when specifying a dbStatementSerializer configuration', () => { + const key = 'key'; + const value = 'value'; + const object = { [key]: value }; + + describe('with a valid function', () => { + beforeEach(() => { + create({ + dbStatementSerializer: (commandObj: Record) => { + return JSON.stringify(commandObj); + }, + }); + }); + + it('should properly collect db statement', done => { + const span = trace.getTracer('default').startSpan('insertRootSpan'); + context.with(trace.setSpan(context.active(), span), () => { + collection + .insertOne(object) + .then(() => { + span.end(); + const spans = getTestSpans(); + const operationName = 'mongodb.insert'; + assertSpans( + spans, + operationName, + SpanKind.CLIENT, + 'insert', + false, + true + ); + const mongoSpan = spans.find(s => s.name === operationName); + const dbStatement = JSON.parse( + mongoSpan!.attributes[SemanticAttributes.DB_STATEMENT] as string + ); + assert.strictEqual(dbStatement[key], value); + done(); + }) + .catch(err => { + done(err); + }); + }); + }); + }); + + describe('with an invalid function', () => { + beforeEach(() => { + create({ + enhancedDatabaseReporting: true, + dbStatementSerializer: (_commandObj: Record) => { + throw new Error('something went wrong!'); + }, + }); + }); + + it('should not do any harm when throwing an exception', done => { + const span = trace.getTracer('default').startSpan('insertRootSpan'); + context.with(trace.setSpan(context.active(), span), () => { + collection + .insertOne(object) + .then(() => { + span.end(); + const spans = getTestSpans(); + assertSpans(spans, 'mongodb.insert', SpanKind.CLIENT, 'insert'); + done(); + }) + .catch(err => { + done(err); + }); + }); + }); + }); + }); + + describe('when specifying a responseHook configuration', () => { + const dataAttributeName = 'mongodb_data'; + describe('with a valid function', () => { + beforeEach(() => { + create({ + responseHook: (span: Span, result: MongoResponseHookInformation) => { + span.setAttribute(dataAttributeName, JSON.stringify(result.data)); + }, + }); + }); + + it('should attach response hook data to the resulting span for insert function', done => { + const insertData = [{ a: 1 }, { a: 2 }, { a: 3 }]; + const span = trace.getTracer('default').startSpan('insertRootSpan'); + context.with(trace.setSpan(context.active(), span), () => { + collection + .insertMany(insertData) + .then(results => { + span.end(); + const spans = getTestSpans(); + const insertSpan = spans[0]; + assert.deepStrictEqual( + JSON.parse(insertSpan.attributes[dataAttributeName] as string) + .n, + results?.insertedCount + ); + + done(); + }) + .catch(err => { + done(err); + }); + }); + }); + + it('should attach response hook data to the resulting span for find function', done => { + const span = trace.getTracer('default').startSpan('findRootSpan'); + context.with(trace.setSpan(context.active(), span), () => { + collection + .find({ a: 1 }) + .toArray() + .then(results => { + span.end(); + const spans = getTestSpans(); + const findSpan = spans[0]; + const hookAttributeValue = JSON.parse( + findSpan.attributes[dataAttributeName] as string + ); + + if (results) { + assert.strictEqual( + hookAttributeValue?.cursor?.firstBatch[0]._id, + results[0]._id.toString() + ); + } else { + throw new Error('Got an unexpected Results: ' + results); + } + done(); + }) + .catch(err => { + done(err); + }); + }); + }); + }); + + describe('with an invalid function', () => { + beforeEach(() => { + create({ + responseHook: (span: Span, result: MongoResponseHookInformation) => { + throw 'some error'; + }, + }); + }); + it('should not do any harm when throwing an exception', done => { + const span = trace.getTracer('default').startSpan('findRootSpan'); + context.with(trace.setSpan(context.active(), span), () => { + collection + .find({ a: 1 }) + .toArray() + .then(() => { + span.end(); + const spans = getTestSpans(); + assertSpans(spans, 'mongodb.find', SpanKind.CLIENT, 'find'); + done(); + }) + .catch(err => { + done(err); + }); + }); + }); + }); + }); + + describe('Mixed operations with callback', () => { + it('should create a span for find after callback insert', done => { + const insertData = [{ a: 1 }, { a: 2 }, { a: 3 }]; + const span = trace.getTracer('default').startSpan('insertRootSpan'); + context.with(trace.setSpan(context.active(), span), () => { + collection + .insertMany(insertData) + .then(() => { + span.end(); + const spans = getTestSpans(); + const mainSpan = spans[spans.length - 1]; + assertSpans(spans, 'mongodb.insert', SpanKind.CLIENT, 'insert'); + resetMemoryExporter(); + + collection + .find({ a: 1 }) + .toArray() + .then(() => { + const spans2 = getTestSpans(); + spans2.push(mainSpan); + assertSpans(spans2, 'mongodb.find', SpanKind.CLIENT, 'find'); + assert.strictEqual( + mainSpan.spanContext().spanId, + spans2[0].parentSpanId + ); + done(); + }) + .catch(err => { + done(err); + }); + }) + .catch(err => { + done(err); + }); + }); + }); + }); + + /** Should intercept command */ + describe('Removing Instrumentation', () => { + it('should unpatch plugin', () => { + assert.doesNotThrow(() => { + instrumentation.disable(); + }); + }); + + it('should not create a child span for query', done => { + const insertData = [{ a: 1 }, { a: 2 }, { a: 3 }]; + const span = trace.getTracer('default').startSpan('insertRootSpan'); + collection + .insertMany(insertData) + .then(() => { + span.end(); + assert.strictEqual(getTestSpans().length, 1); + done(); + }) + .catch(err => { + done(err); + }); + }); + + it('should not create a child span for cursor', done => { + const span = trace.getTracer('default').startSpan('findRootSpan'); + collection + .find({}) + .toArray() + .then(() => { + span.end(); + assert.strictEqual(getTestSpans().length, 1); + done(); + }) + .catch(err => { + assert.ifError(err); + done(err); + }); + }); + + it('should not create a child span for command', done => { + const span = trace.getTracer('default').startSpan('indexRootSpan'); + collection + .createIndex({ a: 1 }) + .then(() => { + span.end(); + assert.strictEqual(getTestSpans().length, 1); + done(); + }) + .catch(err => { + done(err); + }); + }); + }); +}); From 914c399a80505df857683331cce310ab2334a924 Mon Sep 17 00:00:00 2001 From: Guillaume Deconinck Date: Sun, 2 Apr 2023 13:27:48 +0900 Subject: [PATCH 02/14] refactor(mongodb): avoid duplicating code for v4 & v5 --- .../src/instrumentation.ts | 178 ++++++++---------- 1 file changed, 82 insertions(+), 96 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts index 6cb7c576cc..0a091f9aad 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts @@ -21,19 +21,19 @@ import { Span, SpanKind, SpanStatusCode, -} from '@opentelemetry/api'; +} from "@opentelemetry/api"; import { InstrumentationBase, InstrumentationNodeModuleDefinition, InstrumentationNodeModuleFile, isWrapped, safeExecuteInTheMiddle, -} from '@opentelemetry/instrumentation'; +} from "@opentelemetry/instrumentation"; import { DbSystemValues, SemanticAttributes, -} from '@opentelemetry/semantic-conventions'; -import { MongoDBInstrumentationConfig, CommandResult } from './types'; +} from "@opentelemetry/semantic-conventions"; +import { MongoDBInstrumentationConfig, CommandResult } from "./types"; import { CursorState, MongodbCommandType, @@ -41,13 +41,13 @@ import { MongoInternalTopology, WireProtocolInternal, V4Connection, -} from './internal-types'; -import { VERSION } from './version'; +} from "./internal-types"; +import { VERSION } from "./version"; /** mongodb instrumentation plugin for OpenTelemetry */ export class MongoDBInstrumentation extends InstrumentationBase { constructor(protected override _config: MongoDBInstrumentationConfig = {}) { - super('@opentelemetry/instrumentation-mongodb', VERSION, _config); + super("@opentelemetry/instrumentation-mongodb", VERSION, _config); } init() { @@ -56,42 +56,28 @@ export class MongoDBInstrumentation extends InstrumentationBase { return [ new InstrumentationNodeModuleDefinition( - 'mongodb', - ['>=3.3 <4'], + "mongodb", + [">=3.3 <4"], undefined, undefined, [ new InstrumentationNodeModuleFile( - 'mongodb/lib/core/wireprotocol/index.js', - ['>=3.3 <4'], + "mongodb/lib/core/wireprotocol/index.js", + [">=3.3 <4"], v3Patch, v3Unpatch ), ] ), new InstrumentationNodeModuleDefinition( - 'mongodb', - ['4.*'], + "mongodb", + ["4.*", "5.*"], undefined, undefined, [ new InstrumentationNodeModuleFile( - 'mongodb/lib/cmap/connection.js', - ['4.*'], - v4Patch, - v4Unpatch - ), - ] - ), - new InstrumentationNodeModuleDefinition( - 'mongodb', - ['5.*'], - undefined, - undefined, - [ - new InstrumentationNodeModuleFile( - 'mongodb/lib/cmap/connection.js', - ['5.*'], + "mongodb/lib/cmap/connection.js", + ["4.*", "5.*"], v4Patch, v4Unpatch ), @@ -106,57 +92,57 @@ export class MongoDBInstrumentation extends InstrumentationBase { diag.debug(`Applying patch for mongodb@${moduleVersion}`); // patch insert operation if (isWrapped(moduleExports.insert)) { - this._unwrap(moduleExports, 'insert'); + this._unwrap(moduleExports, "insert"); } this._wrap( moduleExports, - 'insert', - this._getV3PatchOperation('insert') + "insert", + this._getV3PatchOperation("insert") ); // patch remove operation if (isWrapped(moduleExports.remove)) { - this._unwrap(moduleExports, 'remove'); + this._unwrap(moduleExports, "remove"); } this._wrap( moduleExports, - 'remove', - this._getV3PatchOperation('remove') + "remove", + this._getV3PatchOperation("remove") ); // patch update operation if (isWrapped(moduleExports.update)) { - this._unwrap(moduleExports, 'update'); + this._unwrap(moduleExports, "update"); } this._wrap( moduleExports, - 'update', - this._getV3PatchOperation('update') + "update", + this._getV3PatchOperation("update") ); // patch other command if (isWrapped(moduleExports.command)) { - this._unwrap(moduleExports, 'command'); + this._unwrap(moduleExports, "command"); } - this._wrap(moduleExports, 'command', this._getV3PatchCommand()); + this._wrap(moduleExports, "command", this._getV3PatchCommand()); // patch query if (isWrapped(moduleExports.query)) { - this._unwrap(moduleExports, 'query'); + this._unwrap(moduleExports, "query"); } - this._wrap(moduleExports, 'query', this._getV3PatchFind()); + this._wrap(moduleExports, "query", this._getV3PatchFind()); // patch get more operation on cursor if (isWrapped(moduleExports.getMore)) { - this._unwrap(moduleExports, 'getMore'); + this._unwrap(moduleExports, "getMore"); } - this._wrap(moduleExports, 'getMore', this._getV3PatchCursor()); + this._wrap(moduleExports, "getMore", this._getV3PatchCursor()); return moduleExports; }, v3Unpatch: (moduleExports?: T, moduleVersion?: string) => { if (moduleExports === undefined) return; diag.debug(`Removing internal patch for mongodb@${moduleVersion}`); - this._unwrap(moduleExports, 'insert'); - this._unwrap(moduleExports, 'remove'); - this._unwrap(moduleExports, 'update'); - this._unwrap(moduleExports, 'command'); - this._unwrap(moduleExports, 'query'); - this._unwrap(moduleExports, 'getMore'); + this._unwrap(moduleExports, "insert"); + this._unwrap(moduleExports, "remove"); + this._unwrap(moduleExports, "update"); + this._unwrap(moduleExports, "command"); + this._unwrap(moduleExports, "query"); + this._unwrap(moduleExports, "getMore"); }, }; } @@ -168,12 +154,12 @@ export class MongoDBInstrumentation extends InstrumentationBase { diag.debug(`Applying patch for mongodb@${moduleVersion}`); // patch insert operation if (isWrapped(moduleExports.Connection.prototype.command)) { - this._unwrap(moduleExports.Connection.prototype, 'command'); + this._unwrap(moduleExports.Connection.prototype, "command"); } this._wrap( moduleExports.Connection.prototype, - 'command', + "command", this._getV4PatchCommand() ); return moduleExports; @@ -181,13 +167,13 @@ export class MongoDBInstrumentation extends InstrumentationBase { v4Unpatch: (moduleExports?: any, moduleVersion?: string) => { if (moduleExports === undefined) return; diag.debug(`Removing internal patch for mongodb@${moduleVersion}`); - this._unwrap(moduleExports.Connection.prototype, 'command'); + this._unwrap(moduleExports.Connection.prototype, "command"); }, }; } /** Creates spans for common operations */ - private _getV3PatchOperation(operationName: 'insert' | 'update' | 'remove') { + private _getV3PatchOperation(operationName: "insert" | "update" | "remove") { const instrumentation = this; return (original: WireProtocolInternal[typeof operationName]) => { return function patchedServerCommand( @@ -200,13 +186,13 @@ export class MongoDBInstrumentation extends InstrumentationBase { ) { const currentSpan = trace.getSpan(context.active()); const resultHandler = - typeof options === 'function' ? options : callback; + typeof options === "function" ? options : callback; if ( !currentSpan || - typeof resultHandler !== 'function' || - typeof ops !== 'object' + typeof resultHandler !== "function" || + typeof ops !== "object" ) { - if (typeof options === 'function') { + if (typeof options === "function") { return original.call(this, server, ns, ops, options); } else { return original.call(this, server, ns, ops, options, callback); @@ -229,7 +215,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { ); const patchedCallback = instrumentation._patchEnd(span, resultHandler); // handle when options is the callback to send the correct number of args - if (typeof options === 'function') { + if (typeof options === "function") { return original.call(this, server, ns, ops, patchedCallback); } else { return original.call(this, server, ns, ops, options, patchedCallback); @@ -241,7 +227,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { /** Creates spans for command operation */ private _getV3PatchCommand() { const instrumentation = this; - return (original: WireProtocolInternal['command']) => { + return (original: WireProtocolInternal["command"]) => { return function patchedServerCommand( this: unknown, server: MongoInternalTopology, @@ -252,13 +238,13 @@ export class MongoDBInstrumentation extends InstrumentationBase { ) { const currentSpan = trace.getSpan(context.active()); const resultHandler = - typeof options === 'function' ? options : callback; + typeof options === "function" ? options : callback; if ( !currentSpan || - typeof resultHandler !== 'function' || - typeof cmd !== 'object' + typeof resultHandler !== "function" || + typeof cmd !== "object" ) { - if (typeof options === 'function') { + if (typeof options === "function") { return original.call(this, server, ns, cmd, options); } else { return original.call(this, server, ns, cmd, options, callback); @@ -266,7 +252,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { } const commandType = MongoDBInstrumentation._getCommandType(cmd); const type = - commandType === MongodbCommandType.UNKNOWN ? 'command' : commandType; + commandType === MongodbCommandType.UNKNOWN ? "command" : commandType; const span = instrumentation.tracer.startSpan(`mongodb.${type}`, { kind: SpanKind.CLIENT, }); @@ -275,7 +261,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { instrumentation._populateV3Attributes(span, ns, server, cmd, operation); const patchedCallback = instrumentation._patchEnd(span, resultHandler); // handle when options is the callback to send the correct number of args - if (typeof options === 'function') { + if (typeof options === "function") { return original.call(this, server, ns, cmd, patchedCallback); } else { return original.call(this, server, ns, cmd, options, patchedCallback); @@ -287,7 +273,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { /** Creates spans for command operation */ private _getV4PatchCommand() { const instrumentation = this; - return (original: V4Connection['command']) => { + return (original: V4Connection["command"]) => { return function patchedV4ServerCommand( this: unknown, ns: any, @@ -299,8 +285,8 @@ export class MongoDBInstrumentation extends InstrumentationBase { const resultHandler = callback; if ( !currentSpan || - typeof resultHandler !== 'function' || - typeof cmd !== 'object' || + typeof resultHandler !== "function" || + typeof cmd !== "object" || cmd.ismaster || cmd.hello ) { @@ -323,7 +309,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { /** Creates spans for find operation */ private _getV3PatchFind() { const instrumentation = this; - return (original: WireProtocolInternal['query']) => { + return (original: WireProtocolInternal["query"]) => { return function patchedServerCommand( this: unknown, server: MongoInternalTopology, @@ -335,13 +321,13 @@ export class MongoDBInstrumentation extends InstrumentationBase { ) { const currentSpan = trace.getSpan(context.active()); const resultHandler = - typeof options === 'function' ? options : callback; + typeof options === "function" ? options : callback; if ( !currentSpan || - typeof resultHandler !== 'function' || - typeof cmd !== 'object' + typeof resultHandler !== "function" || + typeof cmd !== "object" ) { - if (typeof options === 'function') { + if (typeof options === "function") { return original.call(this, server, ns, cmd, cursorState, options); } else { return original.call( @@ -355,13 +341,13 @@ export class MongoDBInstrumentation extends InstrumentationBase { ); } } - const span = instrumentation.tracer.startSpan('mongodb.find', { + const span = instrumentation.tracer.startSpan("mongodb.find", { kind: SpanKind.CLIENT, }); - instrumentation._populateV3Attributes(span, ns, server, cmd, 'find'); + instrumentation._populateV3Attributes(span, ns, server, cmd, "find"); const patchedCallback = instrumentation._patchEnd(span, resultHandler); // handle when options is the callback to send the correct number of args - if (typeof options === 'function') { + if (typeof options === "function") { return original.call( this, server, @@ -388,7 +374,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { /** Creates spans for find operation */ private _getV3PatchCursor() { const instrumentation = this; - return (original: WireProtocolInternal['getMore']) => { + return (original: WireProtocolInternal["getMore"]) => { return function patchedServerCommand( this: unknown, server: MongoInternalTopology, @@ -400,9 +386,9 @@ export class MongoDBInstrumentation extends InstrumentationBase { ) { const currentSpan = trace.getSpan(context.active()); const resultHandler = - typeof options === 'function' ? options : callback; - if (!currentSpan || typeof resultHandler !== 'function') { - if (typeof options === 'function') { + typeof options === "function" ? options : callback; + if (!currentSpan || typeof resultHandler !== "function") { + if (typeof options === "function") { return original.call( this, server, @@ -423,7 +409,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { ); } } - const span = instrumentation.tracer.startSpan('mongodb.getMore', { + const span = instrumentation.tracer.startSpan("mongodb.getMore", { kind: SpanKind.CLIENT, }); instrumentation._populateV3Attributes( @@ -431,11 +417,11 @@ export class MongoDBInstrumentation extends InstrumentationBase { ns, server, cursorState.cmd, - 'getMore' + "getMore" ); const patchedCallback = instrumentation._patchEnd(span, resultHandler); // handle when options is the callback to send the correct number of args - if (typeof options === 'function') { + if (typeof options === "function") { return original.call( this, server, @@ -496,9 +482,9 @@ export class MongoDBInstrumentation extends InstrumentationBase { let host, port: undefined | string; if (connectionCtx) { const hostParts = - typeof connectionCtx.address === 'string' - ? connectionCtx.address.split(':') - : ''; + typeof connectionCtx.address === "string" + ? connectionCtx.address.split(":") + : ""; if (hostParts.length === 2) { host = hostParts[0]; port = hostParts[1]; @@ -548,7 +534,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { if (host == null || port == null) { const address = topology.description?.address; if (address) { - const addressSegments = address.split(':'); + const addressSegments = address.split(":"); host = addressSegments[0]; port = addressSegments[1]; } @@ -559,7 +545,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { // collection or index, like so: [database-name].[collection-or-index-name]. // It could be a string or an instance of MongoDBNamespace, as such we // always coerce to a string to extract db and collection. - const [dbName, dbCollection] = ns.toString().split('.'); + const [dbName, dbCollection] = ns.toString().split("."); // capture parameters within the query as well if enhancedDatabaseReporting is enabled. const commandObj = command?.query ?? command?.q ?? command; @@ -599,7 +585,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { } if (!commandObj) return; const dbStatementSerializer = - typeof this._config.dbStatementSerializer === 'function' + typeof this._config.dbStatementSerializer === "function" ? this._config.dbStatementSerializer : this._defaultDbStatementSerializer.bind(this); @@ -608,9 +594,9 @@ export class MongoDBInstrumentation extends InstrumentationBase { const query = dbStatementSerializer(commandObj); span.setAttribute(SemanticAttributes.DB_STATEMENT, query); }, - err => { + (err) => { if (err) { - this._diag.error('Error running dbStatementSerializer hook', err); + this._diag.error("Error running dbStatementSerializer hook", err); } }, true @@ -622,7 +608,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { const resultObj = enhancedDbReporting ? commandObj : Object.keys(commandObj).reduce((obj, key) => { - obj[key] = '?'; + obj[key] = "?"; return obj; }, {} as { [key: string]: unknown }); return JSON.stringify(resultObj); @@ -635,14 +621,14 @@ export class MongoDBInstrumentation extends InstrumentationBase { */ private _handleExecutionResult(span: Span, result: CommandResult) { const config: MongoDBInstrumentationConfig = this.getConfig(); - if (typeof config.responseHook === 'function') { + if (typeof config.responseHook === "function") { safeExecuteInTheMiddle( () => { config.responseHook!(span, { data: result }); }, - err => { + (err) => { if (err) { - this._diag.error('Error running response hook', err); + this._diag.error("Error running response hook", err); } }, true From cded0c1de36c40d6ba545cfc5738eb925e86bc48 Mon Sep 17 00:00:00 2001 From: Guillaume Deconinck Date: Sun, 2 Apr 2023 13:32:48 +0900 Subject: [PATCH 03/14] fix: lint --- .../src/instrumentation.ts | 164 +++++++++--------- 1 file changed, 82 insertions(+), 82 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts index 0a091f9aad..354d16610a 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts @@ -21,19 +21,19 @@ import { Span, SpanKind, SpanStatusCode, -} from "@opentelemetry/api"; +} from '@opentelemetry/api'; import { InstrumentationBase, InstrumentationNodeModuleDefinition, InstrumentationNodeModuleFile, isWrapped, safeExecuteInTheMiddle, -} from "@opentelemetry/instrumentation"; +} from '@opentelemetry/instrumentation'; import { DbSystemValues, SemanticAttributes, -} from "@opentelemetry/semantic-conventions"; -import { MongoDBInstrumentationConfig, CommandResult } from "./types"; +} from '@opentelemetry/semantic-conventions'; +import { MongoDBInstrumentationConfig, CommandResult } from './types'; import { CursorState, MongodbCommandType, @@ -41,13 +41,13 @@ import { MongoInternalTopology, WireProtocolInternal, V4Connection, -} from "./internal-types"; -import { VERSION } from "./version"; +} from './internal-types'; +import { VERSION } from './version'; /** mongodb instrumentation plugin for OpenTelemetry */ export class MongoDBInstrumentation extends InstrumentationBase { constructor(protected override _config: MongoDBInstrumentationConfig = {}) { - super("@opentelemetry/instrumentation-mongodb", VERSION, _config); + super('@opentelemetry/instrumentation-mongodb', VERSION, _config); } init() { @@ -56,28 +56,28 @@ export class MongoDBInstrumentation extends InstrumentationBase { return [ new InstrumentationNodeModuleDefinition( - "mongodb", - [">=3.3 <4"], + 'mongodb', + ['>=3.3 <4'], undefined, undefined, [ new InstrumentationNodeModuleFile( - "mongodb/lib/core/wireprotocol/index.js", - [">=3.3 <4"], + 'mongodb/lib/core/wireprotocol/index.js', + ['>=3.3 <4'], v3Patch, v3Unpatch ), ] ), new InstrumentationNodeModuleDefinition( - "mongodb", - ["4.*", "5.*"], + 'mongodb', + ['4.*', '5.*'], undefined, undefined, [ new InstrumentationNodeModuleFile( - "mongodb/lib/cmap/connection.js", - ["4.*", "5.*"], + 'mongodb/lib/cmap/connection.js', + ['4.*', '5.*'], v4Patch, v4Unpatch ), @@ -92,57 +92,57 @@ export class MongoDBInstrumentation extends InstrumentationBase { diag.debug(`Applying patch for mongodb@${moduleVersion}`); // patch insert operation if (isWrapped(moduleExports.insert)) { - this._unwrap(moduleExports, "insert"); + this._unwrap(moduleExports, 'insert'); } this._wrap( moduleExports, - "insert", - this._getV3PatchOperation("insert") + 'insert', + this._getV3PatchOperation('insert') ); // patch remove operation if (isWrapped(moduleExports.remove)) { - this._unwrap(moduleExports, "remove"); + this._unwrap(moduleExports, 'remove'); } this._wrap( moduleExports, - "remove", - this._getV3PatchOperation("remove") + 'remove', + this._getV3PatchOperation('remove') ); // patch update operation if (isWrapped(moduleExports.update)) { - this._unwrap(moduleExports, "update"); + this._unwrap(moduleExports, 'update'); } this._wrap( moduleExports, - "update", - this._getV3PatchOperation("update") + 'update', + this._getV3PatchOperation('update') ); // patch other command if (isWrapped(moduleExports.command)) { - this._unwrap(moduleExports, "command"); + this._unwrap(moduleExports, 'command'); } - this._wrap(moduleExports, "command", this._getV3PatchCommand()); + this._wrap(moduleExports, 'command', this._getV3PatchCommand()); // patch query if (isWrapped(moduleExports.query)) { - this._unwrap(moduleExports, "query"); + this._unwrap(moduleExports, 'query'); } - this._wrap(moduleExports, "query", this._getV3PatchFind()); + this._wrap(moduleExports, 'query', this._getV3PatchFind()); // patch get more operation on cursor if (isWrapped(moduleExports.getMore)) { - this._unwrap(moduleExports, "getMore"); + this._unwrap(moduleExports, 'getMore'); } - this._wrap(moduleExports, "getMore", this._getV3PatchCursor()); + this._wrap(moduleExports, 'getMore', this._getV3PatchCursor()); return moduleExports; }, v3Unpatch: (moduleExports?: T, moduleVersion?: string) => { if (moduleExports === undefined) return; diag.debug(`Removing internal patch for mongodb@${moduleVersion}`); - this._unwrap(moduleExports, "insert"); - this._unwrap(moduleExports, "remove"); - this._unwrap(moduleExports, "update"); - this._unwrap(moduleExports, "command"); - this._unwrap(moduleExports, "query"); - this._unwrap(moduleExports, "getMore"); + this._unwrap(moduleExports, 'insert'); + this._unwrap(moduleExports, 'remove'); + this._unwrap(moduleExports, 'update'); + this._unwrap(moduleExports, 'command'); + this._unwrap(moduleExports, 'query'); + this._unwrap(moduleExports, 'getMore'); }, }; } @@ -154,12 +154,12 @@ export class MongoDBInstrumentation extends InstrumentationBase { diag.debug(`Applying patch for mongodb@${moduleVersion}`); // patch insert operation if (isWrapped(moduleExports.Connection.prototype.command)) { - this._unwrap(moduleExports.Connection.prototype, "command"); + this._unwrap(moduleExports.Connection.prototype, 'command'); } this._wrap( moduleExports.Connection.prototype, - "command", + 'command', this._getV4PatchCommand() ); return moduleExports; @@ -167,13 +167,13 @@ export class MongoDBInstrumentation extends InstrumentationBase { v4Unpatch: (moduleExports?: any, moduleVersion?: string) => { if (moduleExports === undefined) return; diag.debug(`Removing internal patch for mongodb@${moduleVersion}`); - this._unwrap(moduleExports.Connection.prototype, "command"); + this._unwrap(moduleExports.Connection.prototype, 'command'); }, }; } /** Creates spans for common operations */ - private _getV3PatchOperation(operationName: "insert" | "update" | "remove") { + private _getV3PatchOperation(operationName: 'insert' | 'update' | 'remove') { const instrumentation = this; return (original: WireProtocolInternal[typeof operationName]) => { return function patchedServerCommand( @@ -186,13 +186,13 @@ export class MongoDBInstrumentation extends InstrumentationBase { ) { const currentSpan = trace.getSpan(context.active()); const resultHandler = - typeof options === "function" ? options : callback; + typeof options === 'function' ? options : callback; if ( !currentSpan || - typeof resultHandler !== "function" || - typeof ops !== "object" + typeof resultHandler !== 'function' || + typeof ops !== 'object' ) { - if (typeof options === "function") { + if (typeof options === 'function') { return original.call(this, server, ns, ops, options); } else { return original.call(this, server, ns, ops, options, callback); @@ -215,7 +215,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { ); const patchedCallback = instrumentation._patchEnd(span, resultHandler); // handle when options is the callback to send the correct number of args - if (typeof options === "function") { + if (typeof options === 'function') { return original.call(this, server, ns, ops, patchedCallback); } else { return original.call(this, server, ns, ops, options, patchedCallback); @@ -227,7 +227,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { /** Creates spans for command operation */ private _getV3PatchCommand() { const instrumentation = this; - return (original: WireProtocolInternal["command"]) => { + return (original: WireProtocolInternal['command']) => { return function patchedServerCommand( this: unknown, server: MongoInternalTopology, @@ -238,13 +238,13 @@ export class MongoDBInstrumentation extends InstrumentationBase { ) { const currentSpan = trace.getSpan(context.active()); const resultHandler = - typeof options === "function" ? options : callback; + typeof options === 'function' ? options : callback; if ( !currentSpan || - typeof resultHandler !== "function" || - typeof cmd !== "object" + typeof resultHandler !== 'function' || + typeof cmd !== 'object' ) { - if (typeof options === "function") { + if (typeof options === 'function') { return original.call(this, server, ns, cmd, options); } else { return original.call(this, server, ns, cmd, options, callback); @@ -252,7 +252,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { } const commandType = MongoDBInstrumentation._getCommandType(cmd); const type = - commandType === MongodbCommandType.UNKNOWN ? "command" : commandType; + commandType === MongodbCommandType.UNKNOWN ? 'command' : commandType; const span = instrumentation.tracer.startSpan(`mongodb.${type}`, { kind: SpanKind.CLIENT, }); @@ -261,7 +261,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { instrumentation._populateV3Attributes(span, ns, server, cmd, operation); const patchedCallback = instrumentation._patchEnd(span, resultHandler); // handle when options is the callback to send the correct number of args - if (typeof options === "function") { + if (typeof options === 'function') { return original.call(this, server, ns, cmd, patchedCallback); } else { return original.call(this, server, ns, cmd, options, patchedCallback); @@ -273,7 +273,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { /** Creates spans for command operation */ private _getV4PatchCommand() { const instrumentation = this; - return (original: V4Connection["command"]) => { + return (original: V4Connection['command']) => { return function patchedV4ServerCommand( this: unknown, ns: any, @@ -285,8 +285,8 @@ export class MongoDBInstrumentation extends InstrumentationBase { const resultHandler = callback; if ( !currentSpan || - typeof resultHandler !== "function" || - typeof cmd !== "object" || + typeof resultHandler !== 'function' || + typeof cmd !== 'object' || cmd.ismaster || cmd.hello ) { @@ -309,7 +309,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { /** Creates spans for find operation */ private _getV3PatchFind() { const instrumentation = this; - return (original: WireProtocolInternal["query"]) => { + return (original: WireProtocolInternal['query']) => { return function patchedServerCommand( this: unknown, server: MongoInternalTopology, @@ -321,13 +321,13 @@ export class MongoDBInstrumentation extends InstrumentationBase { ) { const currentSpan = trace.getSpan(context.active()); const resultHandler = - typeof options === "function" ? options : callback; + typeof options === 'function' ? options : callback; if ( !currentSpan || - typeof resultHandler !== "function" || - typeof cmd !== "object" + typeof resultHandler !== 'function' || + typeof cmd !== 'object' ) { - if (typeof options === "function") { + if (typeof options === 'function') { return original.call(this, server, ns, cmd, cursorState, options); } else { return original.call( @@ -341,13 +341,13 @@ export class MongoDBInstrumentation extends InstrumentationBase { ); } } - const span = instrumentation.tracer.startSpan("mongodb.find", { + const span = instrumentation.tracer.startSpan('mongodb.find', { kind: SpanKind.CLIENT, }); - instrumentation._populateV3Attributes(span, ns, server, cmd, "find"); + instrumentation._populateV3Attributes(span, ns, server, cmd, 'find'); const patchedCallback = instrumentation._patchEnd(span, resultHandler); // handle when options is the callback to send the correct number of args - if (typeof options === "function") { + if (typeof options === 'function') { return original.call( this, server, @@ -374,7 +374,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { /** Creates spans for find operation */ private _getV3PatchCursor() { const instrumentation = this; - return (original: WireProtocolInternal["getMore"]) => { + return (original: WireProtocolInternal['getMore']) => { return function patchedServerCommand( this: unknown, server: MongoInternalTopology, @@ -386,9 +386,9 @@ export class MongoDBInstrumentation extends InstrumentationBase { ) { const currentSpan = trace.getSpan(context.active()); const resultHandler = - typeof options === "function" ? options : callback; - if (!currentSpan || typeof resultHandler !== "function") { - if (typeof options === "function") { + typeof options === 'function' ? options : callback; + if (!currentSpan || typeof resultHandler !== 'function') { + if (typeof options === 'function') { return original.call( this, server, @@ -409,7 +409,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { ); } } - const span = instrumentation.tracer.startSpan("mongodb.getMore", { + const span = instrumentation.tracer.startSpan('mongodb.getMore', { kind: SpanKind.CLIENT, }); instrumentation._populateV3Attributes( @@ -417,11 +417,11 @@ export class MongoDBInstrumentation extends InstrumentationBase { ns, server, cursorState.cmd, - "getMore" + 'getMore' ); const patchedCallback = instrumentation._patchEnd(span, resultHandler); // handle when options is the callback to send the correct number of args - if (typeof options === "function") { + if (typeof options === 'function') { return original.call( this, server, @@ -482,9 +482,9 @@ export class MongoDBInstrumentation extends InstrumentationBase { let host, port: undefined | string; if (connectionCtx) { const hostParts = - typeof connectionCtx.address === "string" - ? connectionCtx.address.split(":") - : ""; + typeof connectionCtx.address === 'string' + ? connectionCtx.address.split(':') + : ''; if (hostParts.length === 2) { host = hostParts[0]; port = hostParts[1]; @@ -534,7 +534,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { if (host == null || port == null) { const address = topology.description?.address; if (address) { - const addressSegments = address.split(":"); + const addressSegments = address.split(':'); host = addressSegments[0]; port = addressSegments[1]; } @@ -545,7 +545,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { // collection or index, like so: [database-name].[collection-or-index-name]. // It could be a string or an instance of MongoDBNamespace, as such we // always coerce to a string to extract db and collection. - const [dbName, dbCollection] = ns.toString().split("."); + const [dbName, dbCollection] = ns.toString().split('.'); // capture parameters within the query as well if enhancedDatabaseReporting is enabled. const commandObj = command?.query ?? command?.q ?? command; @@ -585,7 +585,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { } if (!commandObj) return; const dbStatementSerializer = - typeof this._config.dbStatementSerializer === "function" + typeof this._config.dbStatementSerializer === 'function' ? this._config.dbStatementSerializer : this._defaultDbStatementSerializer.bind(this); @@ -594,9 +594,9 @@ export class MongoDBInstrumentation extends InstrumentationBase { const query = dbStatementSerializer(commandObj); span.setAttribute(SemanticAttributes.DB_STATEMENT, query); }, - (err) => { + err => { if (err) { - this._diag.error("Error running dbStatementSerializer hook", err); + this._diag.error('Error running dbStatementSerializer hook', err); } }, true @@ -608,7 +608,7 @@ export class MongoDBInstrumentation extends InstrumentationBase { const resultObj = enhancedDbReporting ? commandObj : Object.keys(commandObj).reduce((obj, key) => { - obj[key] = "?"; + obj[key] = '?'; return obj; }, {} as { [key: string]: unknown }); return JSON.stringify(resultObj); @@ -621,14 +621,14 @@ export class MongoDBInstrumentation extends InstrumentationBase { */ private _handleExecutionResult(span: Span, result: CommandResult) { const config: MongoDBInstrumentationConfig = this.getConfig(); - if (typeof config.responseHook === "function") { + if (typeof config.responseHook === 'function') { safeExecuteInTheMiddle( () => { config.responseHook!(span, { data: result }); }, - (err) => { + err => { if (err) { - this._diag.error("Error running response hook", err); + this._diag.error('Error running response hook', err); } }, true From 7d2eeadfc4719de7aadd393d8a82e0f96fe8de4f Mon Sep 17 00:00:00 2001 From: Guillaume Deconinck Date: Sun, 2 Apr 2023 20:04:25 +0900 Subject: [PATCH 04/14] refactor(mongodb): use range for mongodb version check --- .../src/instrumentation.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts index 354d16610a..069735b2f9 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts @@ -71,13 +71,13 @@ export class MongoDBInstrumentation extends InstrumentationBase { ), new InstrumentationNodeModuleDefinition( 'mongodb', - ['4.*', '5.*'], + ['>=4 <6'], undefined, undefined, [ new InstrumentationNodeModuleFile( 'mongodb/lib/cmap/connection.js', - ['4.*', '5.*'], + ['>=4 <6'], v4Patch, v4Unpatch ), From e9118d3eb066e3a1d777744da724892dedba9650 Mon Sep 17 00:00:00 2001 From: Guillaume Deconinck Date: Sat, 6 May 2023 14:17:34 +0900 Subject: [PATCH 05/14] chore(mongodb): make test commands consistent --- plugins/node/opentelemetry-instrumentation-mongodb/.tav.yml | 2 +- plugins/node/opentelemetry-instrumentation-mongodb/package.json | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/.tav.yml b/plugins/node/opentelemetry-instrumentation-mongodb/.tav.yml index 4751a63619..86a2bf927d 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/.tav.yml +++ b/plugins/node/opentelemetry-instrumentation-mongodb/.tav.yml @@ -1,7 +1,7 @@ mongodb: jobs: - versions: ">=3.3 <4" - commands: npm run test + commands: npm run test-v3 - versions: ">=4 <5" commands: npm run test-v4 - versions: ">=5 <6" diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/package.json b/plugins/node/opentelemetry-instrumentation-mongodb/package.json index 3bac20d841..245cf6debd 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/package.json +++ b/plugins/node/opentelemetry-instrumentation-mongodb/package.json @@ -7,7 +7,7 @@ "repository": "open-telemetry/opentelemetry-js-contrib", "scripts": { "docker:start": "docker run -e MONGODB_DB=opentelemetry-tests -e MONGODB_PORT=27017 -e MONGODB_HOST=127.0.0.1 -p 27017:27017 --rm mongo", - "test": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v3.test.ts'", + "test-v3": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v3.test.ts'", "test-v4": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v4.test.ts'", "test-v5": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v5.test.ts'", "test-all-versions": "tav", From bf14baeb7a5ae42c73c3bd9cbcdb37dca081eee5 Mon Sep 17 00:00:00 2001 From: Guillaume Deconinck Date: Wed, 31 May 2023 21:22:18 +0900 Subject: [PATCH 06/14] refactor(mongodb): adapt code based on main's changes --- .../package.json | 6 +- .../src/instrumentation.ts | 8 +- .../test/mongodb-v3.test.ts | 2 +- ....test.ts => mongodb-v4-v5.metrics.test.ts} | 51 +++++++---- .../test/mongodb-v4.test.ts | 69 ++++++++------- .../test/mongodb-v5.test.ts | 88 +++++++++++++------ 6 files changed, 142 insertions(+), 82 deletions(-) rename plugins/node/opentelemetry-instrumentation-mongodb/test/{mongodb-v4.metrics.test.ts => mongodb-v4-v5.metrics.test.ts} (86%) diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/package.json b/plugins/node/opentelemetry-instrumentation-mongodb/package.json index bbcd0850fd..c66c6be12e 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/package.json +++ b/plugins/node/opentelemetry-instrumentation-mongodb/package.json @@ -8,8 +8,8 @@ "scripts": { "docker:start": "docker run -e MONGODB_DB=opentelemetry-tests -e MONGODB_PORT=27017 -e MONGODB_HOST=127.0.0.1 -p 27017:27017 --rm mongo", "test-v3": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v3.test.ts'", - "test-v4": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v4**.test.ts'", - "test-v5": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v5.test.ts'", + "test-v4": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/mongodb-v4-v5.metrics.test.ts' 'test/**/mongodb-v4.test.ts'", + "test-v5": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/mongodb-v4-v5.metrics.test.ts' 'test/**/mongodb-v5.test.ts'", "test-all-versions": "tav", "tdd": "npm run test -- --watch-extensions ts --watch", "clean": "rimraf build/*", @@ -61,7 +61,7 @@ "@types/mongodb": "3.6.20", "@types/node": "18.11.7", "mocha": "7.2.0", - "mongodb": "3.6.11", + "mongodb": "^4", "nyc": "15.1.0", "rimraf": "5.0.0", "test-all-versions": "5.0.1", diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts b/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts index d6b14a8664..587c0fe185 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/src/instrumentation.ts @@ -95,25 +95,25 @@ export class MongoDBInstrumentation extends InstrumentationBase { ), new InstrumentationNodeModuleDefinition( 'mongodb', - ['>=4'], + ['4.*', '5.*'], undefined, undefined, [ new InstrumentationNodeModuleFile( 'mongodb/lib/cmap/connection.js', - ['4.*'], + ['4.*', '5.*'], v4PatchConnection, v4UnpatchConnection ), new InstrumentationNodeModuleFile( 'mongodb/lib/cmap/connect.js', - ['4.*'], + ['4.*', '5.*'], v4PatchConnect, v4UnpatchConnect ), new InstrumentationNodeModuleFile( 'mongodb/lib/sessions.js', - ['4.*'], + ['4.*', '5.*'], v4PatchSessions, v4UnpatchSessions ), diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v3.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v3.test.ts index f3368d75fc..a8f0444839 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v3.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v3.test.ts @@ -35,7 +35,7 @@ import * as mongodb from 'mongodb'; import { assertSpans, accessCollection, DEFAULT_MONGO_HOST } from './utils'; import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; -describe('MongoDBInstrumentation', () => { +describe('MongoDBInstrumentation-Tracing-v3', () => { function create(config: MongoDBInstrumentationConfig = {}) { instrumentation.setConfig(config); } diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.metrics.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts similarity index 86% rename from plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.metrics.test.ts rename to plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts index b6fb8c36d1..e7edfbb426 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.metrics.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts @@ -28,7 +28,27 @@ import { ResourceMetrics, } from '@opentelemetry/sdk-metrics'; -import * as mongodb from 'mongodb'; +import { + getInstrumentation, + registerInstrumentationTesting, +} from '@opentelemetry/contrib-test-utils'; + +import * as assert from 'assert'; + +// Get instrumentation (singleton) +let instrumentation: MongoDBInstrumentation; +{ + const instance: MongoDBInstrumentation | undefined = getInstrumentation(); + if (!instance) { + instrumentation = new MongoDBInstrumentation(); + registerInstrumentationTesting(instrumentation); + } else { + instrumentation = instance; + } +} + +import { accessCollection, DEFAULT_MONGO_HOST } from './utils'; +import { MongoClient } from 'mongodb'; const otelTestingMeterProvider = new MeterProvider(); const inMemoryMetricsExporter = new InMemoryMetricExporter( @@ -42,17 +62,8 @@ const metricReader = new PeriodicExportingMetricReader({ otelTestingMeterProvider.addMetricReader(metricReader); -import { registerInstrumentationTesting } from '@opentelemetry/contrib-test-utils'; -const instrumentation = registerInstrumentationTesting( - new MongoDBInstrumentation() -); - instrumentation.setMeterProvider(otelTestingMeterProvider); -import { accessCollection, DEFAULT_MONGO_HOST } from './utils'; - -import * as assert from 'assert'; - async function waitForNumberOfExports( exporter: InMemoryMetricExporter, numberOfExports: number @@ -83,12 +94,11 @@ describe('MongoDBInstrumentation-Metrics', () => { const HOST = process.env.MONGODB_HOST || DEFAULT_MONGO_HOST; const PORT = process.env.MONGODB_PORT || '27017'; - const DB_NAME = process.env.MONGODB_DB || 'opentelemetry-tests-metrics'; + const DB_NAME = process.env.MONGODB_DB || 'opentelemetry-tests'; const COLLECTION_NAME = 'test-metrics'; const URL = `mongodb://${HOST}:${PORT}/${DB_NAME}`; + let client: MongoClient; - let client: mongodb.MongoClient; - let collection: mongodb.Collection; beforeEach(function mongoBeforeEach(done) { // Skipping all tests in beforeEach() is a workaround. Mocha does not work // properly when skipping tests in before() on nested describe() calls. @@ -96,6 +106,7 @@ describe('MongoDBInstrumentation-Metrics', () => { if (!shouldTest) { this.skip(); } + inMemoryMetricsExporter.reset(); done(); }); @@ -103,11 +114,11 @@ describe('MongoDBInstrumentation-Metrics', () => { it('Should add connection usage metrics', async () => { const result = await accessCollection(URL, DB_NAME, COLLECTION_NAME); client = result.client; - collection = result.collection; + const collection = result.collection; const insertData = [{ a: 1 }, { a: 2 }, { a: 3 }]; await collection.insertMany(insertData); await collection.deleteMany({}); - let exportedMetrics = await waitForNumberOfExports( + const exportedMetrics = await waitForNumberOfExports( inMemoryMetricsExporter, 1 ); @@ -140,11 +151,17 @@ describe('MongoDBInstrumentation-Metrics', () => { metrics[0].dataPoints[1].attributes['pool.name'], `mongodb://${HOST}:${PORT}/${DB_NAME}` ); + }); + + it('Should add disconnection usage metrics', async () => { await client.close(); - exportedMetrics = await waitForNumberOfExports(inMemoryMetricsExporter, 2); + const exportedMetrics = await waitForNumberOfExports( + inMemoryMetricsExporter, + 2 + ); assert.strictEqual(exportedMetrics.length, 2); - metrics = exportedMetrics[1].scopeMetrics[0].metrics; + const metrics = exportedMetrics[1].scopeMetrics[0].metrics; assert.strictEqual(metrics.length, 1); assert.strictEqual(metrics[0].dataPointType, DataPointType.SUM); diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts index 10025b8a74..7314fa6ac6 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts @@ -18,23 +18,35 @@ import { context, trace, SpanKind, Span } from '@opentelemetry/api'; import * as assert from 'assert'; -import { MongoDBInstrumentation, MongoDBInstrumentationConfig } from '../src'; -import { MongoResponseHookInformation } from '../src'; import { + MongoDBInstrumentation, + MongoDBInstrumentationConfig, + MongoResponseHookInformation, +} from '../src'; +import { + getInstrumentation, registerInstrumentationTesting, getTestSpans, resetMemoryExporter, } from '@opentelemetry/contrib-test-utils'; -const instrumentation = registerInstrumentationTesting( - new MongoDBInstrumentation() -); +// Get instrumentation (singleton) +let instrumentation: MongoDBInstrumentation; +{ + const instance: MongoDBInstrumentation | undefined = getInstrumentation(); + if (!instance) { + instrumentation = new MongoDBInstrumentation(); + registerInstrumentationTesting(instrumentation); + } else { + instrumentation = instance; + } +} import * as mongodb from 'mongodb'; import { assertSpans, accessCollection, DEFAULT_MONGO_HOST } from './utils'; import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; -describe('MongoDBInstrumentation-Tracing', () => { +describe('MongoDBInstrumentation-Tracing-v4', () => { function create(config: MongoDBInstrumentationConfig = {}) { instrumentation.setConfig(config); } @@ -47,12 +59,11 @@ describe('MongoDBInstrumentation-Tracing', () => { shouldTest = false; } - const URL = `mongodb://${process.env.MONGODB_HOST || DEFAULT_MONGO_HOST}:${ - process.env.MONGODB_PORT || '27017' - }`; - const DB_NAME = process.env.MONGODB_DB || 'opentelemetry-tests-traces'; + const HOST = process.env.MONGODB_HOST || DEFAULT_MONGO_HOST; + const PORT = process.env.MONGODB_PORT || '27017'; + const DB_NAME = process.env.MONGODB_DB || 'opentelemetry-tests'; const COLLECTION_NAME = 'test-traces'; - const conn_string = `${URL}/${DB_NAME}`; + const URL = `mongodb://${HOST}:${PORT}/${DB_NAME}`; let client: mongodb.MongoClient; let collection: mongodb.Collection; @@ -95,9 +106,9 @@ describe('MongoDBInstrumentation-Tracing', () => { done(); }); - after(() => { + after(async () => { if (client) { - client.close(); + await client.close(); } }); @@ -116,7 +127,7 @@ describe('MongoDBInstrumentation-Tracing', () => { 'mongodb.insert', SpanKind.CLIENT, 'insert', - conn_string + URL ); done(); }) @@ -138,7 +149,7 @@ describe('MongoDBInstrumentation-Tracing', () => { 'mongodb.update', SpanKind.CLIENT, 'update', - conn_string + URL ); done(); }) @@ -160,7 +171,7 @@ describe('MongoDBInstrumentation-Tracing', () => { 'mongodb.delete', SpanKind.CLIENT, 'delete', - conn_string + URL ); done(); }) @@ -186,7 +197,7 @@ describe('MongoDBInstrumentation-Tracing', () => { 'mongodb.find', SpanKind.CLIENT, 'find', - conn_string + URL ); done(); }) @@ -215,7 +226,7 @@ describe('MongoDBInstrumentation-Tracing', () => { 'mongodb.find', SpanKind.CLIENT, 'find', - conn_string + URL ); // assert that we correctly got the first as a find assertSpans( @@ -225,7 +236,7 @@ describe('MongoDBInstrumentation-Tracing', () => { 'mongodb.getMore', SpanKind.CLIENT, 'getMore', - conn_string + URL ); done(); }) @@ -251,7 +262,7 @@ describe('MongoDBInstrumentation-Tracing', () => { 'mongodb.createIndexes', SpanKind.CLIENT, 'createIndexes', - conn_string + URL ); done(); }) @@ -287,7 +298,7 @@ describe('MongoDBInstrumentation-Tracing', () => { operationName, SpanKind.CLIENT, 'insert', - conn_string, + URL, false, false ); @@ -333,7 +344,7 @@ describe('MongoDBInstrumentation-Tracing', () => { operationName, SpanKind.CLIENT, 'insert', - conn_string, + URL, false, true ); @@ -374,7 +385,7 @@ describe('MongoDBInstrumentation-Tracing', () => { 'mongodb.insert', SpanKind.CLIENT, 'insert', - conn_string + URL ); done(); }) @@ -469,13 +480,7 @@ describe('MongoDBInstrumentation-Tracing', () => { .then(() => { span.end(); const spans = getTestSpans(); - assertSpans( - spans, - 'mongodb.find', - SpanKind.CLIENT, - 'find', - conn_string - ); + assertSpans(spans, 'mongodb.find', SpanKind.CLIENT, 'find', URL); done(); }) .catch(err => { @@ -502,7 +507,7 @@ describe('MongoDBInstrumentation-Tracing', () => { 'mongodb.insert', SpanKind.CLIENT, 'insert', - conn_string + URL ); resetMemoryExporter(); @@ -517,7 +522,7 @@ describe('MongoDBInstrumentation-Tracing', () => { 'mongodb.find', SpanKind.CLIENT, 'find', - conn_string + URL ); assert.strictEqual( mainSpan.spanContext().spanId, diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts index 2b493ba3c4..ec398f049c 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts @@ -18,23 +18,35 @@ import { context, trace, SpanKind, Span } from '@opentelemetry/api'; import * as assert from 'assert'; -import { MongoDBInstrumentation, MongoDBInstrumentationConfig } from '../src'; -import { MongoResponseHookInformation } from '../src'; import { + MongoDBInstrumentation, + MongoDBInstrumentationConfig, + MongoResponseHookInformation, +} from '../src'; +import { + getInstrumentation, registerInstrumentationTesting, getTestSpans, resetMemoryExporter, } from '@opentelemetry/contrib-test-utils'; -const instrumentation = registerInstrumentationTesting( - new MongoDBInstrumentation() -); +// Get instrumentation (singleton) +let instrumentation: MongoDBInstrumentation; +{ + const instance: MongoDBInstrumentation | undefined = getInstrumentation(); + if (!instance) { + instrumentation = new MongoDBInstrumentation(); + registerInstrumentationTesting(instrumentation); + } else { + instrumentation = instance; + } +} import * as mongodb from 'mongodb'; import { assertSpans, accessCollection, DEFAULT_MONGO_HOST } from './utils'; import { SemanticAttributes } from '@opentelemetry/semantic-conventions'; -describe('MongoDBInstrumentation', () => { +describe('MongoDBInstrumentation-Tracing-v5', () => { function create(config: MongoDBInstrumentationConfig = {}) { instrumentation.setConfig(config); } @@ -47,17 +59,16 @@ describe('MongoDBInstrumentation', () => { shouldTest = false; } - const URL = `mongodb://${process.env.MONGODB_HOST || DEFAULT_MONGO_HOST}:${ - process.env.MONGODB_PORT || '27017' - }`; + const HOST = process.env.MONGODB_HOST || DEFAULT_MONGO_HOST; + const PORT = process.env.MONGODB_PORT || '27017'; const DB_NAME = process.env.MONGODB_DB || 'opentelemetry-tests'; - const COLLECTION_NAME = 'test'; + const COLLECTION_NAME = 'test-traces'; + const URL = `mongodb://${HOST}:${PORT}/${DB_NAME}`; let client: mongodb.MongoClient; let collection: mongodb.Collection; before(done => { - shouldTest = true; accessCollection(URL, DB_NAME, COLLECTION_NAME) .then(result => { client = result.client; @@ -88,13 +99,13 @@ describe('MongoDBInstrumentation', () => { afterEach(async () => { if (shouldTest) { - await collection.deleteMany({}); + await collection.deleteMany(); } }); - after(() => { + after(async () => { if (client) { - client.close(); + await client.close(); } }); @@ -112,7 +123,8 @@ describe('MongoDBInstrumentation', () => { getTestSpans(), 'mongodb.insert', SpanKind.CLIENT, - 'insert' + 'insert', + URL ); done(); }) @@ -133,7 +145,8 @@ describe('MongoDBInstrumentation', () => { getTestSpans(), 'mongodb.update', SpanKind.CLIENT, - 'update' + 'update', + URL ); done(); }) @@ -154,7 +167,8 @@ describe('MongoDBInstrumentation', () => { getTestSpans(), 'mongodb.delete', SpanKind.CLIENT, - 'delete' + 'delete', + URL ); done(); }) @@ -179,7 +193,8 @@ describe('MongoDBInstrumentation', () => { getTestSpans(), 'mongodb.find', SpanKind.CLIENT, - 'find' + 'find', + URL ); done(); }) @@ -207,7 +222,8 @@ describe('MongoDBInstrumentation', () => { ), 'mongodb.find', SpanKind.CLIENT, - 'find' + 'find', + URL ); // assert that we correctly got the first as a find assertSpans( @@ -216,7 +232,8 @@ describe('MongoDBInstrumentation', () => { ), 'mongodb.getMore', SpanKind.CLIENT, - 'getMore' + 'getMore', + URL ); done(); }) @@ -241,7 +258,8 @@ describe('MongoDBInstrumentation', () => { getTestSpans(), 'mongodb.createIndexes', SpanKind.CLIENT, - 'createIndexes' + 'createIndexes', + URL ); done(); }) @@ -277,6 +295,7 @@ describe('MongoDBInstrumentation', () => { operationName, SpanKind.CLIENT, 'insert', + URL, false, false ); @@ -322,6 +341,7 @@ describe('MongoDBInstrumentation', () => { operationName, SpanKind.CLIENT, 'insert', + URL, false, true ); @@ -357,7 +377,13 @@ describe('MongoDBInstrumentation', () => { .then(() => { span.end(); const spans = getTestSpans(); - assertSpans(spans, 'mongodb.insert', SpanKind.CLIENT, 'insert'); + assertSpans( + spans, + 'mongodb.insert', + SpanKind.CLIENT, + 'insert', + URL + ); done(); }) .catch(err => { @@ -451,7 +477,7 @@ describe('MongoDBInstrumentation', () => { .then(() => { span.end(); const spans = getTestSpans(); - assertSpans(spans, 'mongodb.find', SpanKind.CLIENT, 'find'); + assertSpans(spans, 'mongodb.find', SpanKind.CLIENT, 'find', URL); done(); }) .catch(err => { @@ -473,7 +499,13 @@ describe('MongoDBInstrumentation', () => { span.end(); const spans = getTestSpans(); const mainSpan = spans[spans.length - 1]; - assertSpans(spans, 'mongodb.insert', SpanKind.CLIENT, 'insert'); + assertSpans( + spans, + 'mongodb.insert', + SpanKind.CLIENT, + 'insert', + URL + ); resetMemoryExporter(); collection @@ -482,7 +514,13 @@ describe('MongoDBInstrumentation', () => { .then(() => { const spans2 = getTestSpans(); spans2.push(mainSpan); - assertSpans(spans2, 'mongodb.find', SpanKind.CLIENT, 'find'); + assertSpans( + spans2, + 'mongodb.find', + SpanKind.CLIENT, + 'find', + URL + ); assert.strictEqual( mainSpan.spanContext().spanId, spans2[0].parentSpanId From 582c6a48c68d9e60fd5b7f87f1ba03a7a54f1a73 Mon Sep 17 00:00:00 2001 From: Guillaume Deconinck Date: Wed, 31 May 2023 21:23:53 +0900 Subject: [PATCH 07/14] chore: revert mongodb bump in devDependencies --- plugins/node/opentelemetry-instrumentation-mongodb/package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/package.json b/plugins/node/opentelemetry-instrumentation-mongodb/package.json index c66c6be12e..7dd9c829f3 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/package.json +++ b/plugins/node/opentelemetry-instrumentation-mongodb/package.json @@ -61,7 +61,7 @@ "@types/mongodb": "3.6.20", "@types/node": "18.11.7", "mocha": "7.2.0", - "mongodb": "^4", + "mongodb": "3.6.11", "nyc": "15.1.0", "rimraf": "5.0.0", "test-all-versions": "5.0.1", From e95ddbf8efe5dc7f57002247335f0cf4d5683473 Mon Sep 17 00:00:00 2001 From: Guillaume Deconinck Date: Tue, 6 Jun 2023 20:30:26 +0900 Subject: [PATCH 08/14] refactor: adapt code based on comments --- .../package.json | 9 +- .../test/mongodb-v4-v5.metrics.test.ts | 102 +++++++++++------- .../test/mongodb-v4.test.ts | 17 +-- 3 files changed, 70 insertions(+), 58 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/package.json b/plugins/node/opentelemetry-instrumentation-mongodb/package.json index 7dd9c829f3..8e4f6aace7 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/package.json +++ b/plugins/node/opentelemetry-instrumentation-mongodb/package.json @@ -7,9 +7,10 @@ "repository": "open-telemetry/opentelemetry-js-contrib", "scripts": { "docker:start": "docker run -e MONGODB_DB=opentelemetry-tests -e MONGODB_PORT=27017 -e MONGODB_HOST=127.0.0.1 -p 27017:27017 --rm mongo", + "test": "npm run test-v3", "test-v3": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v3.test.ts'", - "test-v4": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/mongodb-v4-v5.metrics.test.ts' 'test/**/mongodb-v4.test.ts'", - "test-v5": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/mongodb-v4-v5.metrics.test.ts' 'test/**/mongodb-v5.test.ts'", + "test-v4": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v4.test.ts' 'test/mongodb-v4-v5.metrics.test.ts'", + "test-v5": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v5.test.ts' 'test/mongodb-v4-v5.metrics.test.ts'", "test-all-versions": "tav", "tdd": "npm run test -- --watch-extensions ts --watch", "clean": "rimraf build/*", @@ -61,7 +62,7 @@ "@types/mongodb": "3.6.20", "@types/node": "18.11.7", "mocha": "7.2.0", - "mongodb": "3.6.11", + "mongodb": "4", "nyc": "15.1.0", "rimraf": "5.0.0", "test-all-versions": "5.0.1", @@ -74,4 +75,4 @@ "@opentelemetry/semantic-conventions": "^1.0.0" }, "homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-mongodb#readme" -} +} \ No newline at end of file diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts index e7edfbb426..07d510fde7 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts @@ -21,6 +21,7 @@ import { MongoDBInstrumentation } from '../src'; // TODO: use test-utils after the new package has released. import { AggregationTemporality, + DataPoint, DataPointType, InMemoryMetricExporter, MeterProvider, @@ -28,27 +29,7 @@ import { ResourceMetrics, } from '@opentelemetry/sdk-metrics'; -import { - getInstrumentation, - registerInstrumentationTesting, -} from '@opentelemetry/contrib-test-utils'; - -import * as assert from 'assert'; - -// Get instrumentation (singleton) -let instrumentation: MongoDBInstrumentation; -{ - const instance: MongoDBInstrumentation | undefined = getInstrumentation(); - if (!instance) { - instrumentation = new MongoDBInstrumentation(); - registerInstrumentationTesting(instrumentation); - } else { - instrumentation = instance; - } -} - -import { accessCollection, DEFAULT_MONGO_HOST } from './utils'; -import { MongoClient } from 'mongodb'; +import * as mongodb from 'mongodb'; const otelTestingMeterProvider = new MeterProvider(); const inMemoryMetricsExporter = new InMemoryMetricExporter( @@ -60,28 +41,55 @@ const metricReader = new PeriodicExportingMetricReader({ exportTimeoutMillis: 100, }); -otelTestingMeterProvider.addMetricReader(metricReader); +import { getInstrumentation } from '@opentelemetry/contrib-test-utils'; -instrumentation.setMeterProvider(otelTestingMeterProvider); +const instrumentation: MongoDBInstrumentation | undefined = + getInstrumentation(); + +import { accessCollection, DEFAULT_MONGO_HOST } from './utils'; + +import * as assert from 'assert'; async function waitForNumberOfExports( exporter: InMemoryMetricExporter, - numberOfExports: number + numberOfExports: number, + numberOfDataPoints = 0 ): Promise { if (numberOfExports <= 0) { throw new Error('numberOfExports must be greater than or equal to 0'); } let totalExports = 0; - while (totalExports < numberOfExports) { + let totalDataPoints = 0; + while ( + totalExports < numberOfExports || + totalDataPoints < numberOfDataPoints + ) { await new Promise(resolve => setTimeout(resolve, 20)); const exportedMetrics = exporter.getMetrics(); totalExports = exportedMetrics.length; + if (totalExports > 0) { + totalDataPoints = + exportedMetrics[0].scopeMetrics[0].metrics[0].dataPoints.length; + } } return exporter.getMetrics(); } +function filterDataPointsForDB( + dataPoints: DataPoint[], + dbName: string +): DataPoint[] { + return dataPoints.filter(v => { + const poolName = v?.attributes?.['pool.name']; + if (poolName && typeof poolName === 'string') { + return poolName.includes(dbName); + } + return false; + }); +} + describe('MongoDBInstrumentation-Metrics', () => { // For these tests, mongo must be running. Add RUN_MONGODB_TESTS to run // these tests. @@ -94,10 +102,16 @@ describe('MongoDBInstrumentation-Metrics', () => { const HOST = process.env.MONGODB_HOST || DEFAULT_MONGO_HOST; const PORT = process.env.MONGODB_PORT || '27017'; - const DB_NAME = process.env.MONGODB_DB || 'opentelemetry-tests'; + const DB_NAME = process.env.MONGODB_DB || 'opentelemetry-tests-metrics'; const COLLECTION_NAME = 'test-metrics'; const URL = `mongodb://${HOST}:${PORT}/${DB_NAME}`; - let client: MongoClient; + let client: mongodb.MongoClient; + + before(() => { + instrumentation?.enable(); + otelTestingMeterProvider.addMetricReader(metricReader); + instrumentation?.setMeterProvider(otelTestingMeterProvider); + }); beforeEach(function mongoBeforeEach(done) { // Skipping all tests in beforeEach() is a workaround. Mocha does not work @@ -137,18 +151,21 @@ describe('MongoDBInstrumentation-Metrics', () => { metrics[0].descriptor.name, 'db.client.connections.usage' ); - assert.strictEqual(metrics[0].dataPoints.length, 2); - assert.strictEqual(metrics[0].dataPoints[0].value, 0); - assert.strictEqual(metrics[0].dataPoints[0].attributes['state'], 'used'); + + // Checking dataPoints + const dataPoints = filterDataPointsForDB(metrics[0].dataPoints, DB_NAME); + assert.strictEqual(dataPoints.length, 2); + assert.strictEqual(dataPoints[0].value, 0); + assert.strictEqual(dataPoints[0].attributes['state'], 'used'); assert.strictEqual( - metrics[0].dataPoints[0].attributes['pool.name'], + dataPoints[0].attributes['pool.name'], `mongodb://${HOST}:${PORT}/${DB_NAME}` ); - assert.strictEqual(metrics[0].dataPoints[1].value, 1); - assert.strictEqual(metrics[0].dataPoints[1].attributes['state'], 'idle'); + assert.strictEqual(dataPoints[1].value, 1); + assert.strictEqual(dataPoints[1].attributes['state'], 'idle'); assert.strictEqual( - metrics[0].dataPoints[1].attributes['pool.name'], + dataPoints[1].attributes['pool.name'], `mongodb://${HOST}:${PORT}/${DB_NAME}` ); }); @@ -169,17 +186,20 @@ describe('MongoDBInstrumentation-Metrics', () => { metrics[0].descriptor.description, 'The number of connections that are currently in state described by the state attribute.' ); - assert.strictEqual(metrics[0].dataPoints.length, 2); - assert.strictEqual(metrics[0].dataPoints[0].value, 0); - assert.strictEqual(metrics[0].dataPoints[0].attributes['state'], 'used'); + + // Checking dataPoints + const dataPoints = filterDataPointsForDB(metrics[0].dataPoints, DB_NAME); + assert.strictEqual(dataPoints.length, 2); + assert.strictEqual(dataPoints[0].value, 0); + assert.strictEqual(dataPoints[0].attributes['state'], 'used'); assert.strictEqual( - metrics[0].dataPoints[0].attributes['pool.name'], + dataPoints[0].attributes['pool.name'], `mongodb://${HOST}:${PORT}/${DB_NAME}` ); - assert.strictEqual(metrics[0].dataPoints[1].value, 0); - assert.strictEqual(metrics[0].dataPoints[1].attributes['state'], 'idle'); + assert.strictEqual(dataPoints[1].value, 0); + assert.strictEqual(dataPoints[1].attributes['state'], 'idle'); assert.strictEqual( - metrics[0].dataPoints[1].attributes['pool.name'], + dataPoints[1].attributes['pool.name'], `mongodb://${HOST}:${PORT}/${DB_NAME}` ); }); diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts index 7314fa6ac6..18ba6bc9ef 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4.test.ts @@ -24,23 +24,14 @@ import { MongoResponseHookInformation, } from '../src'; import { - getInstrumentation, registerInstrumentationTesting, getTestSpans, resetMemoryExporter, } from '@opentelemetry/contrib-test-utils'; -// Get instrumentation (singleton) -let instrumentation: MongoDBInstrumentation; -{ - const instance: MongoDBInstrumentation | undefined = getInstrumentation(); - if (!instance) { - instrumentation = new MongoDBInstrumentation(); - registerInstrumentationTesting(instrumentation); - } else { - instrumentation = instance; - } -} +const instrumentation = registerInstrumentationTesting( + new MongoDBInstrumentation() +); import * as mongodb from 'mongodb'; import { assertSpans, accessCollection, DEFAULT_MONGO_HOST } from './utils'; @@ -61,7 +52,7 @@ describe('MongoDBInstrumentation-Tracing-v4', () => { const HOST = process.env.MONGODB_HOST || DEFAULT_MONGO_HOST; const PORT = process.env.MONGODB_PORT || '27017'; - const DB_NAME = process.env.MONGODB_DB || 'opentelemetry-tests'; + const DB_NAME = process.env.MONGODB_DB || 'opentelemetry-tests-traces'; const COLLECTION_NAME = 'test-traces'; const URL = `mongodb://${HOST}:${PORT}/${DB_NAME}`; From 997c6429770ecfd4f11b329e72d8fb5b05f2adbd Mon Sep 17 00:00:00 2001 From: Guillaume Deconinck Date: Tue, 6 Jun 2023 20:56:53 +0900 Subject: [PATCH 09/14] chore: re-use old order for tests suites --- .../node/opentelemetry-instrumentation-mongodb/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/package.json b/plugins/node/opentelemetry-instrumentation-mongodb/package.json index 8e4f6aace7..5b65e5a4db 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/package.json +++ b/plugins/node/opentelemetry-instrumentation-mongodb/package.json @@ -9,8 +9,8 @@ "docker:start": "docker run -e MONGODB_DB=opentelemetry-tests -e MONGODB_PORT=27017 -e MONGODB_HOST=127.0.0.1 -p 27017:27017 --rm mongo", "test": "npm run test-v3", "test-v3": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v3.test.ts'", - "test-v4": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v4.test.ts' 'test/mongodb-v4-v5.metrics.test.ts'", - "test-v5": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v5.test.ts' 'test/mongodb-v4-v5.metrics.test.ts'", + "test-v4": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/mongodb-v4-v5.metrics.test.ts' 'test/**/mongodb-v4.test.ts'", + "test-v5": "nyc ts-mocha -p tsconfig.json --require '@opentelemetry/contrib-test-utils' 'test/mongodb-v4-v5.metrics.test.ts' 'test/**/mongodb-v5.test.ts'", "test-all-versions": "tav", "tdd": "npm run test -- --watch-extensions ts --watch", "clean": "rimraf build/*", From e91dfe0670db83b36653c3b50087161e694c11db Mon Sep 17 00:00:00 2001 From: Guillaume Deconinck Date: Tue, 6 Jun 2023 20:57:01 +0900 Subject: [PATCH 10/14] refactor: simply metrics tests --- .../test/mongodb-v4-v5.metrics.test.ts | 44 ++++--------------- 1 file changed, 9 insertions(+), 35 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts index 07d510fde7..a70d52471e 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts @@ -21,7 +21,6 @@ import { MongoDBInstrumentation } from '../src'; // TODO: use test-utils after the new package has released. import { AggregationTemporality, - DataPoint, DataPointType, InMemoryMetricExporter, MeterProvider, @@ -29,8 +28,6 @@ import { ResourceMetrics, } from '@opentelemetry/sdk-metrics'; -import * as mongodb from 'mongodb'; - const otelTestingMeterProvider = new MeterProvider(); const inMemoryMetricsExporter = new InMemoryMetricExporter( AggregationTemporality.CUMULATIVE @@ -41,55 +38,33 @@ const metricReader = new PeriodicExportingMetricReader({ exportTimeoutMillis: 100, }); -import { getInstrumentation } from '@opentelemetry/contrib-test-utils'; - -const instrumentation: MongoDBInstrumentation | undefined = - getInstrumentation(); +import { registerInstrumentationTesting } from '@opentelemetry/contrib-test-utils'; +const instrumentation = registerInstrumentationTesting( + new MongoDBInstrumentation() +); import { accessCollection, DEFAULT_MONGO_HOST } from './utils'; - +import * as mongodb from 'mongodb'; import * as assert from 'assert'; async function waitForNumberOfExports( exporter: InMemoryMetricExporter, - numberOfExports: number, - numberOfDataPoints = 0 + numberOfExports: number ): Promise { if (numberOfExports <= 0) { throw new Error('numberOfExports must be greater than or equal to 0'); } let totalExports = 0; - let totalDataPoints = 0; - while ( - totalExports < numberOfExports || - totalDataPoints < numberOfDataPoints - ) { + while (totalExports < numberOfExports) { await new Promise(resolve => setTimeout(resolve, 20)); const exportedMetrics = exporter.getMetrics(); totalExports = exportedMetrics.length; - if (totalExports > 0) { - totalDataPoints = - exportedMetrics[0].scopeMetrics[0].metrics[0].dataPoints.length; - } } return exporter.getMetrics(); } -function filterDataPointsForDB( - dataPoints: DataPoint[], - dbName: string -): DataPoint[] { - return dataPoints.filter(v => { - const poolName = v?.attributes?.['pool.name']; - if (poolName && typeof poolName === 'string') { - return poolName.includes(dbName); - } - return false; - }); -} - describe('MongoDBInstrumentation-Metrics', () => { // For these tests, mongo must be running. Add RUN_MONGODB_TESTS to run // these tests. @@ -108,7 +83,6 @@ describe('MongoDBInstrumentation-Metrics', () => { let client: mongodb.MongoClient; before(() => { - instrumentation?.enable(); otelTestingMeterProvider.addMetricReader(metricReader); instrumentation?.setMeterProvider(otelTestingMeterProvider); }); @@ -153,7 +127,7 @@ describe('MongoDBInstrumentation-Metrics', () => { ); // Checking dataPoints - const dataPoints = filterDataPointsForDB(metrics[0].dataPoints, DB_NAME); + const dataPoints = metrics[0].dataPoints; assert.strictEqual(dataPoints.length, 2); assert.strictEqual(dataPoints[0].value, 0); assert.strictEqual(dataPoints[0].attributes['state'], 'used'); @@ -188,7 +162,7 @@ describe('MongoDBInstrumentation-Metrics', () => { ); // Checking dataPoints - const dataPoints = filterDataPointsForDB(metrics[0].dataPoints, DB_NAME); + const dataPoints = metrics[0].dataPoints; assert.strictEqual(dataPoints.length, 2); assert.strictEqual(dataPoints[0].value, 0); assert.strictEqual(dataPoints[0].attributes['state'], 'used'); From 9eacbf0c0dc253189a656517a1810ca905419043 Mon Sep 17 00:00:00 2001 From: Guillaume Deconinck Date: Tue, 6 Jun 2023 21:09:55 +0900 Subject: [PATCH 11/14] test: fix DB name in v5 tests --- .../test/mongodb-v5.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts index ec398f049c..96bb69e8e1 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts @@ -61,7 +61,7 @@ describe('MongoDBInstrumentation-Tracing-v5', () => { const HOST = process.env.MONGODB_HOST || DEFAULT_MONGO_HOST; const PORT = process.env.MONGODB_PORT || '27017'; - const DB_NAME = process.env.MONGODB_DB || 'opentelemetry-tests'; + const DB_NAME = process.env.MONGODB_DB || 'opentelemetry-tests-traces'; const COLLECTION_NAME = 'test-traces'; const URL = `mongodb://${HOST}:${PORT}/${DB_NAME}`; From eb630339ac9719375f2e2a3d6892918e0cb6cf4b Mon Sep 17 00:00:00 2001 From: Guillaume Deconinck Date: Wed, 7 Jun 2023 20:34:41 +0900 Subject: [PATCH 12/14] chore: revert MongoDB to 3.6.11 in package.json --- .../node/opentelemetry-instrumentation-mongodb/package.json | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/package.json b/plugins/node/opentelemetry-instrumentation-mongodb/package.json index 67df95024d..fbc4d386fb 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/package.json +++ b/plugins/node/opentelemetry-instrumentation-mongodb/package.json @@ -62,7 +62,7 @@ "@types/mongodb": "3.6.20", "@types/node": "18.11.7", "mocha": "7.2.0", - "mongodb": "4", + "mongodb": "3.6.11", "nyc": "15.1.0", "rimraf": "5.0.0", "test-all-versions": "5.0.1", @@ -75,4 +75,4 @@ "@opentelemetry/semantic-conventions": "^1.0.0" }, "homepage": "https://github.com/open-telemetry/opentelemetry-js-contrib/tree/main/plugins/node/opentelemetry-instrumentation-mongodb#readme" -} \ No newline at end of file +} From f1237190002211ef629affec6d3e9d662a11e544 Mon Sep 17 00:00:00 2001 From: Guillaume Deconinck Date: Wed, 7 Jun 2023 20:35:59 +0900 Subject: [PATCH 13/14] test: fix compilation issue due to different signatures (v3 vs v5) --- .../test/mongodb-v5.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts index 96bb69e8e1..bd8271cb8d 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v5.test.ts @@ -99,7 +99,7 @@ describe('MongoDBInstrumentation-Tracing-v5', () => { afterEach(async () => { if (shouldTest) { - await collection.deleteMany(); + await collection.deleteMany({}); } }); From df6c7225d007d7bd53173b5a195dc0afdb718fc8 Mon Sep 17 00:00:00 2001 From: Marc Pichler Date: Fri, 30 Jun 2023 11:50:05 +0200 Subject: [PATCH 14/14] fix: lint --- .../test/mongodb-v4-v5.metrics.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts index a70d52471e..189ff458d6 100644 --- a/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts +++ b/plugins/node/opentelemetry-instrumentation-mongodb/test/mongodb-v4-v5.metrics.test.ts @@ -112,7 +112,7 @@ describe('MongoDBInstrumentation-Metrics', () => { ); assert.strictEqual(exportedMetrics.length, 1); - let metrics = exportedMetrics[0].scopeMetrics[0].metrics; + const metrics = exportedMetrics[0].scopeMetrics[0].metrics; assert.strictEqual(metrics.length, 1); assert.strictEqual(metrics[0].dataPointType, DataPointType.SUM);