Skip to content

Commit

Permalink
Merge branch 'open-telemetry:main' into feat/nestjs-core-support-nest…
Browse files Browse the repository at this point in the history
…js11
  • Loading branch information
neilime authored Feb 11, 2025
2 parents 09f29c9 + 7a1e8b3 commit d55f038
Show file tree
Hide file tree
Showing 17 changed files with 376 additions and 47 deletions.
2 changes: 1 addition & 1 deletion CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ features for unmaintained components. At least one sponsor is needed to lift the
adding the requested feature. Sponsors are expected to provide reviews for that feature and be responsive on the issue.

Components marked as unmaintained still receive semantic conventions updates and bugfixes where possible.
[@open-telemetry/javascript-triagers](https://github.com/orgs/open-telemetry/teams/javascript-triagers) may add the
[@open-telemetry/javascript-contrib-triagers](https://github.com/orgs/open-telemetry/teams/javascript-contrib-triagers) may add the
`type:semconv-update` or `bug` label to mark them as exempt from being auto-closed within two weeks.

A component which is unmaintained may be deprecated if there is a problem that is not fixed in a timely manner.
Expand Down
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,15 @@
"test:ci:changed": "nx affected -t test --base=origin/main --head=HEAD",
"test-all-versions": "nx run-many -t test-all-versions",
"changelog": "lerna-changelog",
"lint": "nx run-many -t lint && npm run lint:readme && npm run lint:markdown",
"lint": "nx run-many -t lint && npm run lint:readme && npm run lint:markdown && npm run lint:semconv-deps",
"lint:fix": "nx run-many -t lint:fix && npm run lint:markdown:fix",
"lint:deps": "npx --yes [email protected] --dependencies --production --tags=-knipignore",
"lint:examples": "eslint ./examples/**/*.js",
"lint:examples:fix": "eslint ./examples/**/*.js --fix",
"lint:markdown": "markdownlint-cli2 $(git ls-files '*.md')",
"lint:markdown:fix": "markdownlint-cli2 --fix $(git ls-files '*.md')",
"lint:readme": "nx run-many -t lint:readme"
"lint:readme": "nx run-many -t lint:readme",
"lint:semconv-deps": "./scripts/lint-semconv-deps.mjs"
},
"keywords": [
"opentelemetry",
Expand Down
23 changes: 11 additions & 12 deletions plugins/node/instrumentation-cucumber/test/cucumber.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -84,24 +84,23 @@ describe('CucumberInstrumentation', () => {
providedConfiguration?: Partial<IConfiguration>
) => {
// clean-up require cache to re-register cucumber hooks for a new run
['features/support/world', 'features/step_definitions/steps'].forEach(
search => {
const key = Object.keys(require.cache).find(key =>
key.includes(search)
);
if (key == null) return;
delete require.cache[key];
}
);
[
path.join('features', 'support', 'world'),
path.join('features', 'step_definitions', 'steps'),
].forEach(search => {
const key = Object.keys(require.cache).find(key => key.includes(search));
if (key == null) return;
delete require.cache[key];
});
const featurePath = path.join(__dirname, 'current.feature');
await fs.promises.writeFile(featurePath, feature, 'utf-8');
const { runConfiguration } = await loadConfiguration({
provided: {
...providedConfiguration,
paths: [featurePath],
require: [
path.join(__dirname, 'features/support/world.ts'),
path.join(__dirname, 'features/step_definitions/steps.ts'),
path.join(__dirname, 'features', 'support', 'world.ts'),
path.join(__dirname, 'features', 'step_definitions', 'steps.ts'),
],
},
});
Expand Down Expand Up @@ -170,7 +169,7 @@ describe('CucumberInstrumentation', () => {
assert(parent, 'Expected a parent span');

assert.deepEqual(parent.attributes, {
[SEMATTRS_CODE_FILEPATH]: 'test/current.feature',
[SEMATTRS_CODE_FILEPATH]: path.join('test', 'current.feature'),
[SEMATTRS_CODE_LINENO]: 7,
[SEMATTRS_CODE_FUNCTION]: 'Button pushing',
[SEMATTRS_CODE_NAMESPACE]: 'Basic',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ Mongodb instrumentation has few options available to choose from. You can set th
| [`enhancedDatabaseReporting`](./src/types.ts#L32) | `string` | If true, additional information about query parameters and results will be attached (as `attributes`) to spans representing database operations |
| `responseHook` | `MongoDBInstrumentationExecutionResponseHook` (function) | Function for adding custom attributes from db response |
| `dbStatementSerializer` | `DbStatementSerializer` (function) | Custom serializer function for the db.statement tag |
| `requireParentSpan` | `boolean` | Require a parent span in order to create mongodb spans, default when unset is `true` |

## Semantic Conventions

Expand Down
13 changes: 8 additions & 5 deletions plugins/node/opentelemetry-instrumentation-mongodb/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,15 @@
"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-v5-v6",
"test-v3": "nyc mocha --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v3.test.ts'",
"test-v4": "nyc mocha --require '@opentelemetry/contrib-test-utils' 'test/mongodb-v4-v5-v6.metrics.test.ts' 'test/**/mongodb-v4.test.ts'",
"test-v5-v6": "nyc mocha --require '@opentelemetry/contrib-test-utils' 'test/mongodb-v4-v5-v6.metrics.test.ts' 'test/**/mongodb-v5-v6.test.ts'",
"test": "npm run test-v3 && npm run test-v4 && npm run test-v5-v6 && nyc merge .nyc_output ./coverage/coverage-final.json",
"test-v3": "tav mongodb 3.7.4 npm run test-v3-run",
"test-v4": "tav mongodb 4.17.0 npm run test-v4-run",
"test-v5-v6": "npm run test-v5-v6-run",
"test-v3-run": "nyc --no-clean mocha --require '@opentelemetry/contrib-test-utils' 'test/**/mongodb-v3.test.ts'",
"test-v4-run": "nyc --no-clean mocha --require '@opentelemetry/contrib-test-utils' 'test/mongodb-v4-v5-v6.metrics.test.ts' 'test/**/mongodb-v4.test.ts'",
"test-v5-v6-run": "nyc --no-clean mocha --require '@opentelemetry/contrib-test-utils' 'test/mongodb-v4-v5-v6.metrics.test.ts' 'test/**/mongodb-v5-v6.test.ts'",
"test-all-versions": "tav",
"tdd": "npm run test -- --watch-extensions ts --watch",
"tdd": "npm run test-v5-v6-run -- --watch-extensions ts --watch",
"clean": "rimraf build/*",
"lint": "eslint . --ext .ts",
"lint:fix": "eslint . --ext .ts --fix",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,21 @@ import { V4Connect, V4Session } from './internal-types';
import { PACKAGE_NAME, PACKAGE_VERSION } from './version';
import { UpDownCounter } from '@opentelemetry/api';

const DEFAULT_CONFIG: MongoDBInstrumentationConfig = {
requireParentSpan: true,
};

/** mongodb instrumentation plugin for OpenTelemetry */
export class MongoDBInstrumentation extends InstrumentationBase<MongoDBInstrumentationConfig> {
private _connectionsUsage!: UpDownCounter;
private _poolName!: string;

constructor(config: MongoDBInstrumentationConfig = {}) {
super(PACKAGE_NAME, PACKAGE_VERSION, config);
super(PACKAGE_NAME, PACKAGE_VERSION, { ...DEFAULT_CONFIG, ...config });
}

override setConfig(config: MongoDBInstrumentationConfig = {}) {
super.setConfig({ ...DEFAULT_CONFIG, ...config });
}

override _updateMetricInstruments() {
Expand Down Expand Up @@ -438,10 +446,13 @@ export class MongoDBInstrumentation extends InstrumentationBase<MongoDBInstrumen
callback?: Function
) {
const currentSpan = trace.getSpan(context.active());
const skipInstrumentation =
instrumentation._checkSkipInstrumentation(currentSpan);

const resultHandler =
typeof options === 'function' ? options : callback;
if (
!currentSpan ||
skipInstrumentation ||
typeof resultHandler !== 'function' ||
typeof ops !== 'object'
) {
Expand All @@ -451,6 +462,7 @@ export class MongoDBInstrumentation extends InstrumentationBase<MongoDBInstrumen
return original.call(this, server, ns, ops, options, callback);
}
}

const span = instrumentation.tracer.startSpan(
`mongodb.${operationName}`,
{
Expand Down Expand Up @@ -490,10 +502,14 @@ export class MongoDBInstrumentation extends InstrumentationBase<MongoDBInstrumen
callback?: Function
) {
const currentSpan = trace.getSpan(context.active());
const skipInstrumentation =
instrumentation._checkSkipInstrumentation(currentSpan);

const resultHandler =
typeof options === 'function' ? options : callback;

if (
!currentSpan ||
skipInstrumentation ||
typeof resultHandler !== 'function' ||
typeof cmd !== 'object'
) {
Expand All @@ -503,6 +519,7 @@ export class MongoDBInstrumentation extends InstrumentationBase<MongoDBInstrumen
return original.call(this, server, ns, cmd, options, callback);
}
}

const commandType = MongoDBInstrumentation._getCommandType(cmd);
const type =
commandType === MongodbCommandType.UNKNOWN ? 'command' : commandType;
Expand Down Expand Up @@ -535,20 +552,17 @@ export class MongoDBInstrumentation extends InstrumentationBase<MongoDBInstrumen
callback: any
) {
const currentSpan = trace.getSpan(context.active());
const skipInstrumentation =
instrumentation._checkSkipInstrumentation(currentSpan);
const resultHandler = callback;
const commandType = Object.keys(cmd)[0];

if (
typeof resultHandler !== 'function' ||
typeof cmd !== 'object' ||
cmd.ismaster ||
cmd.hello
) {
if (typeof cmd !== 'object' || cmd.ismaster || cmd.hello) {
return original.call(this, ns, cmd, options, callback);
}

let span = undefined;
if (currentSpan) {
if (!skipInstrumentation) {
span = instrumentation.tracer.startSpan(`mongodb.${commandType}`, {
kind: SpanKind.CLIENT,
});
Expand Down Expand Up @@ -581,6 +595,9 @@ export class MongoDBInstrumentation extends InstrumentationBase<MongoDBInstrumen
) {
const [ns, cmd] = args;
const currentSpan = trace.getSpan(context.active());
const skipInstrumentation =
instrumentation._checkSkipInstrumentation(currentSpan);

const commandType = Object.keys(cmd)[0];
const resultHandler = () => undefined;

Expand All @@ -589,7 +606,7 @@ export class MongoDBInstrumentation extends InstrumentationBase<MongoDBInstrumen
}

let span = undefined;
if (currentSpan) {
if (!skipInstrumentation) {
span = instrumentation.tracer.startSpan(`mongodb.${commandType}`, {
kind: SpanKind.CLIENT,
});
Expand Down Expand Up @@ -634,10 +651,13 @@ export class MongoDBInstrumentation extends InstrumentationBase<MongoDBInstrumen
callback?: Function
) {
const currentSpan = trace.getSpan(context.active());
const skipInstrumentation =
instrumentation._checkSkipInstrumentation(currentSpan);
const resultHandler =
typeof options === 'function' ? options : callback;

if (
!currentSpan ||
skipInstrumentation ||
typeof resultHandler !== 'function' ||
typeof cmd !== 'object'
) {
Expand All @@ -655,6 +675,7 @@ export class MongoDBInstrumentation extends InstrumentationBase<MongoDBInstrumen
);
}
}

const span = instrumentation.tracer.startSpan('mongodb.find', {
kind: SpanKind.CLIENT,
});
Expand Down Expand Up @@ -699,9 +720,13 @@ export class MongoDBInstrumentation extends InstrumentationBase<MongoDBInstrumen
callback?: Function
) {
const currentSpan = trace.getSpan(context.active());
const skipInstrumentation =
instrumentation._checkSkipInstrumentation(currentSpan);

const resultHandler =
typeof options === 'function' ? options : callback;
if (!currentSpan || typeof resultHandler !== 'function') {

if (skipInstrumentation || typeof resultHandler !== 'function') {
if (typeof options === 'function') {
return original.call(
this,
Expand All @@ -723,6 +748,7 @@ export class MongoDBInstrumentation extends InstrumentationBase<MongoDBInstrumen
);
}
}

const span = instrumentation.tracer.startSpan('mongodb.getMore', {
kind: SpanKind.CLIENT,
});
Expand Down Expand Up @@ -1021,4 +1047,10 @@ export class MongoDBInstrumentation extends InstrumentationBase<MongoDBInstrumen
const poolName = `mongodb://${host}:${port}/${database}`;
this._poolName = poolName;
}

private _checkSkipInstrumentation(currentSpan: Span | undefined) {
const requireParentSpan = this.getConfig().requireParentSpan;
const hasNoParentSpan = currentSpan === undefined;
return requireParentSpan === true && hasNoParentSpan;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,11 @@ export interface MongoDBInstrumentationConfig extends InstrumentationConfig {
* Custom serializer function for the db.statement tag
*/
dbStatementSerializer?: DbStatementSerializer;

/**
* Require parent to create mongodb span, default when unset is true
*/
requireParentSpan?: boolean;
}

export interface MongoResponseHookInformation {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,9 @@ import {
SEMATTRS_NET_PEER_PORT,
} from '@opentelemetry/semantic-conventions';

// We can't use @ts-expect-error because it will fail depending on the used mongodb version on tests
/* eslint-disable @typescript-eslint/ban-ts-comment */

describe('MongoDBInstrumentation-Tracing-v3', () => {
function create(config: MongoDBInstrumentationConfig = {}) {
instrumentation.setConfig(config);
Expand Down Expand Up @@ -85,7 +88,7 @@ describe('MongoDBInstrumentation-Tracing-v3', () => {
}
// Non traced insertion of basic data to perform tests
const insertData = [{ a: 1 }, { a: 2 }, { a: 3 }];
// @ts-expect-error -- v5 removed callback support
// @ts-ignore -- v5 removed callback support
collection.insertMany(insertData, (err: any, result: any) => {
resetMemoryExporter();
done();
Expand All @@ -94,7 +97,7 @@ describe('MongoDBInstrumentation-Tracing-v3', () => {

afterEach(done => {
if (shouldTest) {
// @ts-expect-error -- v5 removed callback support
// @ts-ignore -- v5 removed callback support
collection.deleteMany({}, done);
} else {
done();
Expand Down Expand Up @@ -619,7 +622,6 @@ describe('MongoDBInstrumentation-Tracing-v3', () => {
let collection: Collection;
before(done => {
accessCollection(URL, DB_NAME, COLLECTION_NAME, {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
useUnifiedTopology: true,
})
Expand All @@ -642,7 +644,7 @@ describe('MongoDBInstrumentation-Tracing-v3', () => {
it('should generate correct span attributes', done => {
const span = trace.getTracer('default').startSpan('findRootSpan');
context.with(trace.setSpan(context.active(), span), () => {
// @ts-expect-error -- v5 removed callback support
// @ts-ignore -- v5 removed callback support
collection.find({ a: 1 }).toArray((err, results) => {
span.end();
const [mongoSpan] = getTestSpans();
Expand All @@ -669,6 +671,49 @@ describe('MongoDBInstrumentation-Tracing-v3', () => {
});
});

describe('requireParentSpan', () => {
// Resetting the behavior to default to avoid flakes in other tests
beforeEach(() => {
instrumentation.setConfig();
});

afterEach(() => {
instrumentation.setConfig();
});

it('should not create spans without parent span when requireParentSpan is explicitly set to true', done => {
context.with(trace.deleteSpan(context.active()), () => {
collection
.insertOne({ a: 1 })
.then(() => {
assert.strictEqual(getTestSpans().length, 0);
done();
})
.catch(err => {
done(err);
});
});
});

it('should create spans without parent span when requireParentSpan is false', done => {
instrumentation.setConfig({
requireParentSpan: false,
});

context.with(trace.deleteSpan(context.active()), () => {
collection
.insertOne({ a: 1 })
.then(() => {
assert.strictEqual(getTestSpans().length, 1);
done();
})
.catch(err => {
done(err);
});
});
});
});

/** Should intercept command */
describe('Removing Instrumentation', () => {
it('should unpatch plugin', () => {
Expand Down Expand Up @@ -723,3 +768,5 @@ describe('MongoDBInstrumentation-Tracing-v3', () => {
});
});
});

/* eslint-enable @typescript-eslint/ban-ts-comment */
Loading

0 comments on commit d55f038

Please sign in to comment.