-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
feat(mongoose): Instrument mongoose >= 9.7 via native tracing channels #21803
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
logaretm
wants to merge
5
commits into
develop
Choose a base branch
from
awad/mongoose-tracing-channels
base: develop
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+743
−7
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
ff40b0a
feat(mongoose): Add diagnostics_channel integration for mongoose >= 9.7
logaretm 05c8646
refactor(mongoose): Drop test-only reset and redundant subscriber boo…
logaretm 3bca987
style(mongoose): Use block returns and spacing in subscriber guards
logaretm cf25f1d
style(mongoose): Add blank lines before returns following sibling sta…
logaretm 9cbf9df
refactor(mongoose): Rename mongooseChannelIntegration to mongooseInte…
logaretm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
9 changes: 9 additions & 0 deletions
9
dev-packages/node-integration-tests/suites/tracing/mongoose-tracing-channel/instrument.mjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,9 @@ | ||
| import * as Sentry from '@sentry/node'; | ||
| import { loggingTransport } from '@sentry-internal/node-integration-tests'; | ||
|
|
||
| Sentry.init({ | ||
| dsn: 'https://public@dsn.ingest.sentry.io/1337', | ||
| release: '1.0', | ||
| tracesSampleRate: 1.0, | ||
| transport: loggingTransport, | ||
| }); |
48 changes: 48 additions & 0 deletions
48
dev-packages/node-integration-tests/suites/tracing/mongoose-tracing-channel/scenario.mjs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,48 @@ | ||
| import * as Sentry from '@sentry/node'; | ||
| import mongoose from 'mongoose'; | ||
|
|
||
| async function run() { | ||
| await mongoose.connect(process.env.MONGO_URL || ''); | ||
|
|
||
| const BlogPostSchema = new mongoose.Schema({ | ||
| title: String, | ||
| body: String, | ||
| date: Date, | ||
| }); | ||
|
|
||
| const BlogPost = mongoose.model('BlogPost', BlogPostSchema); | ||
|
|
||
| await Sentry.startSpan( | ||
| { | ||
| name: 'Test Transaction', | ||
| op: 'transaction', | ||
| }, | ||
| async () => { | ||
| const post = new BlogPost({ title: 'Test', body: 'Test body', date: new Date() }); | ||
| await post.save(); | ||
|
|
||
| // Filter with a real value, to assert it is redacted out of `db.query.text`. | ||
| await BlogPost.findOne({ title: 'Test' }); | ||
|
|
||
| await BlogPost.aggregate([{ $match: { title: 'Test' } }]); | ||
|
|
||
| await BlogPost.insertMany([ | ||
| { title: 'Insert1', body: 'b', date: new Date() }, | ||
| { title: 'Insert2', body: 'b', date: new Date() }, | ||
| ]); | ||
|
|
||
| await BlogPost.bulkWrite([ | ||
| { insertOne: { document: { title: 'Bulk1', body: 'b', date: new Date() } } }, | ||
| { insertOne: { document: { title: 'Bulk2', body: 'b', date: new Date() } } }, | ||
| ]); | ||
|
|
||
| // Drive a cursor to exercise the `mongoose:cursor:next` channel. | ||
| const cursor = BlogPost.find().cursor(); | ||
| for (let doc = await cursor.next(); doc != null; doc = await cursor.next()) { | ||
| // iterate | ||
| } | ||
| }, | ||
| ); | ||
| } | ||
|
|
||
| run(); |
118 changes: 118 additions & 0 deletions
118
dev-packages/node-integration-tests/suites/tracing/mongoose-tracing-channel/test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| import { MongoMemoryServer } from 'mongodb-memory-server-global'; | ||
| import { afterAll, beforeAll, expect } from 'vitest'; | ||
| import { conditionalTest } from '../../../utils'; | ||
| import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner'; | ||
|
|
||
| // mongoose >= 9.7.0 publishes its operations via `node:diagnostics_channel`, so the SDK subscribes | ||
| // to those channels (`subscribeMongooseDiagnosticChannels`) instead of monkey-patching. This suite | ||
| // pins `^9.7` and asserts the diagnostics-channel path: stable OTel DB semconv attributes, redacted | ||
| // query text, span relationships, and that the legacy IITM patcher does NOT also fire (no double | ||
| // instrumentation). mongoose 9 requires Node >=20.19, so this suite is skipped on older Node. | ||
| conditionalTest({ min: 20 })('Mongoose tracing channel Test', () => { | ||
| let mongoServer: MongoMemoryServer; | ||
|
|
||
| beforeAll(async () => { | ||
| mongoServer = await MongoMemoryServer.create(); | ||
| process.env.MONGO_URL = mongoServer.getUri(); | ||
| }, 30000); | ||
|
|
||
| afterAll(async () => { | ||
| if (mongoServer) { | ||
| await mongoServer.stop(); | ||
| } | ||
| cleanupChildProcesses(); | ||
| }); | ||
|
|
||
| const expectedSpan = (operation: string, extraData: Record<string, unknown> = {}) => | ||
| expect.objectContaining({ | ||
| data: expect.objectContaining({ | ||
| 'db.system.name': 'mongodb', | ||
| 'db.namespace': 'test', | ||
| 'db.collection.name': 'blogposts', | ||
| 'db.operation.name': operation, | ||
| 'server.address': expect.any(String), | ||
| 'server.port': expect.any(Number), | ||
| ...extraData, | ||
| }), | ||
| description: `mongoose.blogposts.${operation}`, | ||
| op: 'db', | ||
| origin: 'auto.db.mongoose.diagnostic_channel', | ||
| }); | ||
|
|
||
| const EXPECTED_TRANSACTION = { | ||
| transaction: 'Test Transaction', | ||
| spans: expect.arrayContaining([ | ||
| expectedSpan('save'), | ||
| // filter values are redacted out of `db.query.text` | ||
| expectedSpan('findOne', { 'db.query.text': '{"title":"?"}' }), | ||
| expectedSpan('aggregate', { 'db.query.text': '[{"$match":{"title":"?"}}]' }), | ||
| expectedSpan('insertMany', { 'db.operation.batch.size': 2 }), | ||
| expectedSpan('bulkWrite', { 'db.operation.batch.size': 2 }), | ||
| // a cursor iteration emits a span per `.next()` via the `mongoose:cursor:next` channel | ||
| expectedSpan('find'), | ||
| ]), | ||
| }; | ||
|
|
||
| createEsmAndCjsTests( | ||
| __dirname, | ||
| 'scenario.mjs', | ||
| 'instrument.mjs', | ||
| (createTestRunner, test) => { | ||
| test('subscribes to mongoose >= 9.7 diagnostics channels with stable semconv attributes', async () => { | ||
| await createTestRunner().expect({ transaction: EXPECTED_TRANSACTION }).start().completed(); | ||
| }); | ||
|
|
||
| test('does not double-instrument: the legacy IITM mongoose patcher does not fire on 9.7', async () => { | ||
| await createTestRunner() | ||
| .expect({ | ||
| transaction: event => { | ||
| const spans = event.spans || []; | ||
| // The monkey-patch path (origin `auto.db.otel.mongoose`) must be inactive on 9.7+. | ||
| expect(spans.find(span => span.origin === 'auto.db.otel.mongoose')).toBeUndefined(); | ||
| // ...while the diagnostics-channel path is active. | ||
| expect(spans.find(span => span.origin === 'auto.db.mongoose.diagnostic_channel')).toBeDefined(); | ||
| }, | ||
| }) | ||
| .start() | ||
| .completed(); | ||
| }); | ||
|
|
||
| test('never leaks raw filter values into db.query.text', async () => { | ||
| await createTestRunner() | ||
| .expect({ | ||
| transaction: event => { | ||
| const spans = event.spans || []; | ||
| for (const span of spans) { | ||
| const queryText = span.data?.['db.query.text']; | ||
| if (typeof queryText === 'string') { | ||
| expect(queryText).not.toContain('Test'); | ||
| } | ||
| } | ||
| }, | ||
| }) | ||
| .start() | ||
| .completed(); | ||
| }); | ||
|
|
||
| test('nests the mongodb driver span under the mongoose channel span', async () => { | ||
| await createTestRunner() | ||
| .expect({ | ||
| transaction: event => { | ||
| const spans = event.spans || []; | ||
| const mongooseSave = spans.find(span => span.description === 'mongoose.blogposts.save'); | ||
| expect(mongooseSave).toBeDefined(); | ||
| // the underlying mongodb driver span must parent to the mongoose channel span, | ||
| // proving the channel span is the active async context for the traced operation | ||
| const driverChild = spans.find( | ||
| span => span.parent_span_id === mongooseSave?.span_id && span.origin === 'auto.db.otel.mongo', | ||
| ); | ||
| expect(driverChild).toBeDefined(); | ||
| }, | ||
| }) | ||
| .start() | ||
| .completed(); | ||
| }); | ||
| }, | ||
| { additionalDependencies: { mongoose: '^9.7' } }, | ||
| ); | ||
| }); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,31 @@ | ||
| import { defineIntegration, type IntegrationFn } from '@sentry/core'; | ||
| import * as dc from 'node:diagnostics_channel'; | ||
| import { subscribeMongooseDiagnosticChannels } from './mongoose-dc-subscriber'; | ||
|
|
||
| const _mongooseIntegration = (() => { | ||
| return { | ||
| name: 'Mongoose', | ||
| setupOnce() { | ||
| // Bail on Node <= 18.18.0, where `tracingChannel` does not exist. | ||
| if (!dc.tracingChannel) { | ||
| return; | ||
| } | ||
|
|
||
| // Subscribe to mongoose's native tracing channels (mongoose >= 9.7). | ||
| // This is a no-op on versions that don't publish to the channels, so it is always safe to call. | ||
| // `bindTracingChannelToSpan` (inside the subscriber) makes the span the active context via | ||
| // `bindStore`, which needs the Sentry OTel context manager — `initOpenTelemetry()` registers | ||
| // that after `setupOnce`, so defer a tick. | ||
| void Promise.resolve().then(() => subscribeMongooseDiagnosticChannels(dc.tracingChannel)); | ||
| }, | ||
| }; | ||
| }) satisfies IntegrationFn; | ||
|
|
||
| /** | ||
| * Auto-instrument the [mongoose](https://www.npmjs.com/package/mongoose) library via its native | ||
| * `node:diagnostics_channel` tracing channels (mongoose >= 9.7). | ||
| * | ||
| * On older mongoose versions the channels are never published to, so this integration is inert and | ||
| * the IITM-based patcher (gated to `< 9.7.0`) handles instrumentation instead. | ||
| */ | ||
| export const mongooseIntegration = defineIntegration(_mongooseIntegration); |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Preload skips mongoose channel subscribe
Medium Severity
For mongoose
>=9.7, diagnostics-channel subscription runs only in the server-utils integrationsetupOnce, whilepreloadOpenTelemetryinvokesinstrumentMongoosealone. The IITM patcher no longer covers9.7+, so mongoose work between preload andSentry.init()(or any preload-only usage) is not traced.Additional Locations (1)
packages/server-utils/src/mongoose/index.ts#L7-L19Reviewed by Cursor Bugbot for commit 9cbf9df. Configure here.