Title: Implement alternative IITM/RITM wrapping utility · Issue #20171 · getsentry/sentry-javascript · GitHub
Open Graph Title: Implement alternative IITM/RITM wrapping utility · Issue #20171 · getsentry/sentry-javascript
X Title: Implement alternative IITM/RITM wrapping utility · Issue #20171 · getsentry/sentry-javascript
Description: Today, we rely on OTELs registerInstrumentation() to register monkey patching for our Node SDK. While there will continue to be a way to use OTEL, we want to also allow a more generic way to register instrumentation without OTEL as well....
Open Graph Description: Today, we rely on OTELs registerInstrumentation() to register monkey patching for our Node SDK. While there will continue to be a way to use OTEL, we want to also allow a more generic way to regist...
X Description: Today, we rely on OTELs registerInstrumentation() to register monkey patching for our Node SDK. While there will continue to be a way to use OTEL, we want to also allow a more generic way to regist...
Opengraph URL: https://github.com/getsentry/sentry-javascript/issues/20171
X: @github
Domain: github.com
IPv4 address: 140.82.114.3
{"@context":"https://schema.org","@type":"DiscussionForumPosting","headline":"Implement alternative IITM/RITM wrapping utility","articleBody":"Today, we rely on OTELs `registerInstrumentation()` to register monkey patching for our Node SDK. While there will continue to be a way to use OTEL, we want to also allow a more generic way to register instrumentation without OTEL as well.\n\n## Goal\n\nReplace `@opentelemetry/instrumentation`'s `InstrumentationBase` + `registerInstrumentations()` with a Sentry-owned `registerModuleWrapper()` primitive. This decouples Sentry's module-patching mechanism from the OTel instrumentation infrastructure while keeping the same underlying IITM/RITM hooks.\n\n---\n\n## How OTel Instrumentation Works Today\n\n### Data Flow\n\n1. **Construction**: `new ConnectInstrumentation()` calls `InstrumentationBase` constructor, which calls `this.init()` to get `InstrumentationNodeModuleDefinition[]`, stores them in `this._modules`, then calls `this.enable()`.\n2. `init()` return value: Each instrumentation defines its targets via `InstrumentationNodeModuleDefinition`:\n\n ```ts\n new InstrumentationNodeModuleDefinition(\n 'connect', // module name\n ['>=3.0.0 \u003c4'], // supported versions (semver)\n (exports) => patch(exports), // patch function\n (exports) => unpatch(exports) // unpatch function (optional)\n )\n ```\n3. `enable()` sets up hooks (the critical piece, in `@opentelemetry/instrumentation/build/src/platform/node/instrumentation.js`):\n * **CJS**: Registers with `RequireInTheMiddleSingleton` (a singleton `require-in-the-middle` Hook with trie-based module matching)\n * **ESM**: Creates `new import-in-the-middle.Hook([moduleName], { internals: true }, hookFn)`\n4. **Hook fires on require/import**: Calls `_onRequire(module, exports, name, baseDir)` which:\n * Reads `baseDir/package.json` to get the package version\n * Checks version against `supportedVersions` using OTel's lightweight semver\n * If matched and enabled, calls `module.patch(exports, version)`\n5. `registerInstrumentations()`: Top-level API that iterates instrumentations and calls `enable()` on each.\n\n### The shimmer layer\n\nOTel has its own shimmer (\\~120 lines, not the npm `shimmer` package). `_wrap(obj, name, wrapper)`:\n\n1. Saves original as `obj[name]`\n2. Calls `wrapper(original)` to get wrapped version\n3. Sets markers (e.g. `__original`, `__wrapped`) so `isWrapped()` can detect patched exports\n4. The Node-specific `InstrumentationBase` overrides `_wrap` to handle ESM Proxy objects\n\n\\--> We can likely replace this with our own `fill` method or something similar\n\n### Key OTel dependencies involved\n\n* `@opentelemetry/instrumentation` — `InstrumentationBase`, `InstrumentationNodeModuleDefinition`, shimmer, `registerInstrumentations()`\n* `require-in-the-middle` — CJS hook\n* `import-in-the-middle` — ESM hook\n* OTel's internal `semver.js` (\\~440 lines, lightweight, no npm `semver` dep)\n* OTel's internal `RequireInTheMiddleSingleton` + `ModuleNameTrie` — singleton RITM with efficient module name matching\n\n---\n\n## How Sentry Uses This Today\n\n### Three patterns for instrumentations\n\n**Pattern A: Third-party OTel instrumentation (direct usage)**\u003cbr>\\~15+ integrations (connect, pg, mongodb, redis, etc.):\n\n```ts\nexport const instrumentConnect = generateInstrumentOnce(\n INTEGRATION_NAME, () => new ConnectInstrumentation()\n);\n```\n\n**Pattern B: Sentry-written class extending** `InstrumentationBase`\u003cbr>\\~16 instrumentations (Express, Hono, FastifyV3, OpenAI, Anthropic, Vercel AI, LangChain, PostgresJs, Firebase, NestJS, Remix, etc.):\n\n```ts\nclass SentryExpressInstrumentation extends InstrumentationBase {\n init(): InstrumentationNodeModuleDefinition[] { ... }\n}\n```\n\n**Pattern C: Diagnostics channel (no real module patching)**\u003cbr>`SentryNodeFetchInstrumentation`, `SentryHttpInstrumentation` — extend `InstrumentationBase` but return `undefined` from `init()` and use `diagnostics_channel` directly.\n\n### The init flow\n\n1. `Sentry.init()` → `initNodeCore()` → `initializeEsmLoader()` (registers IITM loader hook via `module.register()`)\n2. `initOpenTelemetry()` sets up OTel providers\n3. Integrations' `setupOnce()` calls `instrumentXxx()` (created via `generateInstrumentOnce`)\n4. That calls `registerInstrumentations()` → `enable()` → creates RITM + IITM hooks\n5. User code `require('connect')` / `import 'connect'` triggers hook → version check → `patch()`\n\n### Key Sentry files\n\n\u003c!-- linear:table-colwidths:200,200 -->\n| File | Role |\n| -- | -- |\n| `packages/node-core/src/otel/instrument.ts` | `generateInstrumentOnce()` + `registerInstrumentations()` call site |\n| `packages/node-core/src/sdk/esmLoader.ts` | IITM loader hook registration (`module.register()`) |\n| `packages/node-core/src/utils/ensureIsWrapped.ts` | Uses `isWrapped` from `@opentelemetry/instrumentation` |\n| `packages/node/src/integrations/tracing/*.ts` | All Pattern A/B/C instrumentations |\n| `packages/opentelemetry/src/` | OTel provider setup |\n\n---\n\n## Proposed Design\n\n### New API: `registerModuleWrapper()`\n\n```ts\ninterface ModuleWrapperOptions {\n moduleName: string;\n supportedVersions: string[]; // semver ranges, e.g. ['>=3.0.0 \u003c4']\n patch: (moduleExports: any, version?: string) => any;\n files?: Array\u003c{\n name: string; // relative path within the package\n supportedVersions: string[];\n patch: (exports: any, version?: string) => any;\n }>;\n}\n\nfunction registerModuleWrapper(options: ModuleWrapperOptions): void;\n```\n\n### New file structure\n\n```\npackages/node-core/src/module-wrapper/\n index.ts — registerModuleWrapper() + public API\n singleton.ts — RITM singleton (like OTel's RequireInTheMiddleSingleton + ModuleNameTrie)\n semver.ts — vendored lightweight semver satisfies()\n shimmer.ts — wrap + isWrapped utilities (with ESM Proxy awareness)\n version.ts — extractPackageVersion(baseDir) helper\n```\n\n### What gets vendored from OTel\n\n\u003c!-- linear:table-colwidths:200,200,200,200 -->\n| Component | Source | Size | Notes |\n| -- | -- | -- | -- |\n| RITM singleton | `RequireInTheMiddleSingleton` + `ModuleNameTrie` | \\~150 lines | Single RITM hook with trie-based matching |\n| Module version extraction | `InstrumentationBase._onRequire` (partial) | \\~30 lines | Read `package.json` version from baseDir |\n\n### What does NOT get vendored\n\n* OTel tracer/meter/logger provider plumbing (not needed for module wrapping)\n* `InstrumentationAbstract` (we write our own simpler base class)\n* `registerInstrumentations()` (replaced by `registerModuleWrapper()`)\n* The diagnostics channel integration (Pattern C instrumentations don't need module wrapping)\n\n---\n\n## Migration Strategy\n\n### Step 1: Build the primitives\n\nCreate `packages/node-core/src/module-wrapper/` with:\n\n1. `shimmer.ts` — Vendor OTel's shimmer with Proxy-awareness. Must set `__wrapped` / `__original` (or equivalent) so `ensureIsWrapped()` and `isWrapped()` keep working.\n2. `semver.ts` — Vendor OTel's lightweight semver `satisfies()` or use something comparable\n3. `singleton.ts` — RITM singleton with `ModuleNameTrie`. One global RITM hook, register module names into it.\n4. `index.ts` — `registerModuleWrapper()` implementation:\n * Register with RITM singleton for CJS\n * Create `new iitm.Hook()` for ESM (leveraging Sentry's already-registered loader from `initializeEsmLoader()`)\n * On hook invocation: extract version → check semver → call `patch()`\n\n### Step 2: Create `SentryInstrumentationBase` (compatibility layer)\n\nA drop-in replacement for OTel's `InstrumentationBase` that:\n\n* Keeps the same `init()` → `InstrumentationNodeModuleDefinition[]` pattern\n* Uses `registerModuleWrapper()` internally instead of OTel's `enable()` loop\n* Provides `_wrap` / `isWrapped` from our vendored shimmer\n\nThis minimizes migration effort for Pattern B instrumentations — they just change `extends InstrumentationBase` to `extends SentryInstrumentationBase`.\n\n### Step 3: Migrate Pattern B instrumentations\n\nChange all \\~16 Sentry-written instrumentations:\n\n```diff\n- import { InstrumentationBase, InstrumentationNodeModuleDefinition } from '@opentelemetry/instrumentation';\n+ import { SentryInstrumentationBase, InstrumentationNodeModuleDefinition } from '@sentry/node-core';\n\n- class SentryExpressInstrumentation extends InstrumentationBase {\n+ class SentryExpressInstrumentation extends SentryInstrumentationBase {\n```\n\n### Step 4: Migrate Pattern A instrumentations (vendored third-party)\n\nFor each vendored instrumentation (like connect, which we've already started), the patch logic moves out of the OTel class and into a direct `registerModuleWrapper()` call:\n\n```ts\n// Before (using OTel InstrumentationBase)\nexport const instrumentConnect = generateInstrumentOnce(\n 'Connect', () => new ConnectInstrumentation()\n);\n\n// After (using registerModuleWrapper directly)\nexport const instrumentConnect = generateInstrumentOnce('Connect', () =>\n registerModuleWrapper({\n moduleName: 'connect',\n supportedVersions: ['>=3.0.0 \u003c4'],\n patch: (moduleExports) => patchConnect(moduleExports),\n })\n);\n```\n\nThis requires `generateInstrumentOnce` to accept registrations that use `registerModuleWrapper()` (not only OTel `Instrumentation` objects).\n\n### Step 5: Update `generateInstrumentOnce`\n\nCurrently calls `registerInstrumentations()`. Update to:\n\n* Accept both legacy `Instrumentation` objects (for any remaining OTel instrumentations during transition) and `registerModuleWrapper()`-based registrations\n* Eventually remove OTel `registerInstrumentations()` call entirely\n\n### Step 6: Update `ensureIsWrapped`\n\nReplace import of `isWrapped` from `@opentelemetry/instrumentation` with our own shimmer's `isWrapped`.\n\n### Step 7: Remove `@opentelemetry/instrumentation` dependency\n\nOnce all instrumentations are migrated, remove from `@sentry/node-core` and `@sentry/node` package.json.\n\n---\n\n## Potential Challenges\n\n1. **ESM loader hook sharing**: IITM's loader hook (registered by `initializeEsmLoader()`) must be active before any `new iitm.Hook()` is created. Current code already handles this ordering.\n2. **Dual RITM instances**: If users load their own OTel instrumentations alongside Sentry, there will be two RITM hooks. This is unavoidable but acceptable — both will fire independently.\n3. `isWrapped()` compatibility: Our shimmer must expose the same `isWrapped()` behavior (and compatible markers) as OTel's shimmer, so `ensureIsWrapped()` and any code that checks `isWrapped()` still works.\n4. **Pattern C instrumentations**: These don't use module wrapping at all (`init()` returns `undefined`). They just need a simpler base class that provides a tracer — or they can be refactored to not extend any base class.\n5. `InstrumentationNodeModuleDefinition`: All Pattern B instrumentations use this class. We should either vendor it (trivial — it's a simple data holder) or create our own equivalent with the same shape.\n6. `import-in-the-middle` version coupling: IITM is already a direct Sentry dependency. No issue here.\n7. `require-in-the-middle`: Currently a transitive dependency via `@opentelemetry/instrumentation`. After removing that dep, we'll need to add `require-in-the-middle` as a direct dependency of `@sentry/node-core`.\n\n---\n\n## Order of Execution\n\n\u003c!-- linear:table-colwidths:200,200,200 -->\n| Phase | What | Depends On |\n| -- | -- | -- |\n| 1 | Vendor shimmer, semver, RITM singleton into `module-wrapper/` | Nothing |\n| 2 | Implement `registerModuleWrapper()` | Phase 1 |\n| 3 | Create `SentryInstrumentationBase` using `registerModuleWrapper()` | Phase 2 |\n| 4 | Update `ensureIsWrapped` to use vendored shimmer | Phase 1 |\n| 5 | Migrate Pattern B instrumentations to `SentryInstrumentationBase` | Phase 3 |\n| 6 | Vendor remaining Pattern A instrumentations (like connect) | Phase 2 |\n| 7 | Update `generateInstrumentOnce` to support new API | Phase 2 |\n| 8 | Migrate Pattern C instrumentations (simplify, drop base class) | Phase 3 |\n| 9 | Remove `@opentelemetry/instrumentation` dependency | All above |\n","author":{"url":"https://github.com/apps/linear-code","@type":"Person","name":"linear-code"},"datePublished":"2026-04-09T13:05:05Z","url":"https://github.com/getsentry/sentry-javascript/issues/20171"}
| react-profiling | 0 |
| react-import-map | react,react-dom,react-dom/client,react-dom/profiling,react-is,react/compiler-runtime,react/jsx-dev-runtime,react/jsx-runtime,scheduler@b8488ee2c322 |
| route-pattern | /_view_fragments/issues/show/:user_id/:repository/:id/issue_layout(.:format) |
| route-controller | voltron_issues_fragments |
| route-action | issue_layout |
| fetch-nonce | v2:69614a84-52c7-86b8-d202-e8a5e6a9fe58 |
| current-catalog-service-hash | 81bb79d38c15960b92d99bca9288a9108c7a47b18f2423d0f6438c5b7bcd2114 |
| request-id | 8B00:102FBB:2761485:33C2730:6B042BC6 |
| html-safe-nonce | 5e9657a33e5ff71f93913890f4491d53c13412ce7191b9bce5b626ccb69151cf |
| visitor-payload | eyJyZWZlcnJlciI6IiIsInJlcXVlc3RfaWQiOiI4QjAwOjEwMkZCQjoyNzYxNDg1OjMzQzI3MzA6NkIwNDJCQzYiLCJ2aXNpdG9yX2lkIjoiMjI3ODYxMDI1MTE3Nzc5ODU5OCIsInJlZ2lvbl9lZGdlIjoiaWFkIiwicmVnaW9uX3JlbmRlciI6ImlhZCJ9 |
| visitor-hmac | 29642797edaa859eb0d332ff66c023267e0492cebb6778d0e3db24d73b98c007 |
| hovercard-subject-tag | issue:4232446406 |
| github-keyboard-shortcuts | repository,issues,copilot |
| google-site-verification | Apib7-x98H0j5cPqHWwSMm6dNU4GmODRoqxLiDzdx9I |
| octolytics-url | https://collector.github.com/github/collect |
| analytics-location | / |
| fb:app_id | 1401488693436528 |
| apple-itunes-app | app-id=1477376905, app-argument=https://github.com/_view_fragments/issues/show/getsentry/sentry-javascript/20171/issue_layout |
| twitter:image | https://opengraph.githubassets.com/4ebf7602f20f872e1a890b0e8d3ea112b64cae34cbf02b0cf33f97eea2acd5ee/getsentry/sentry-javascript/issues/20171 |
| twitter:card | summary_large_image |
| og:image | https://opengraph.githubassets.com/4ebf7602f20f872e1a890b0e8d3ea112b64cae34cbf02b0cf33f97eea2acd5ee/getsentry/sentry-javascript/issues/20171 |
| og:image:alt | Today, we rely on OTELs registerInstrumentation() to register monkey patching for our Node SDK. While there will continue to be a way to use OTEL, we want to also allow a more generic way to regist... |
| og:image:width | 1200 |
| og:image:height | 600 |
| og:site_name | GitHub |
| og:type | object |
| og:author:username | linear-code[bot] |
| hostname | github.com |
| expected-hostname | github.com |
| None | b7a1d2b9101496921b08579fbee988d014345aef2f5bd660d1f8c7332d81560e |
| turbo-cache-control | no-preview |
| go-import | github.com/getsentry/sentry-javascript git https://github.com/getsentry/sentry-javascript.git |
| octolytics-dimension-user_id | 1396951 |
| octolytics-dimension-user_login | getsentry |
| octolytics-dimension-repository_id | 3328572 |
| octolytics-dimension-repository_nwo | getsentry/sentry-javascript |
| octolytics-dimension-repository_public | true |
| octolytics-dimension-repository_is_fork | false |
| octolytics-dimension-repository_network_root_id | 3328572 |
| octolytics-dimension-repository_network_root_nwo | getsentry/sentry-javascript |
| turbo-body-classes | logged-out env-production page-responsive |
| disable-turbo | false |
| browser-stats-url | https://api.github.com/_private/browser/stats |
| browser-errors-url | https://api.github.com/_private/browser/errors |
| release | c3dd496c3da6ea6b77e69c09279d2b81604654f1 |
| ui-target | full |
| theme-color | #1e2327 |
| color-scheme | light dark |
| react-app-name | issues |
Links:
| Server | github.com |
| Content-Type | text/html; charset=utf-8 |
| Cache-Control | max-age=0, private, must-revalidate |
Viewport: width=device-width