Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions .changeset/otel-active-context.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'@bentocache/otel': patch
---

Fix wrong span parenting. Each cache operation span is now the active context while the operation runs, so:

- cache operations from concurrent requests on the same key no longer end up in another request's trace
- spans created inside a `getOrSet` factory (database queries, nested cache calls) are children of the `cache.factory` span
- the instrumentation scope reports the package version instead of `0.1.0`

This relies on `context.attach()` from `@opentelemetry/api` 1.10, which `AsyncLocalStorageContextManager` (the Node.js SDK default) supports. `manuallyRegister()` now logs a warning when it cannot patch the `BentoCache` constructor, because `suppressInternalOperations` has no effect in that case.
7 changes: 7 additions & 0 deletions .changeset/otel-sdk-3.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'@bentocache/otel': minor
---

Upgrade to OpenTelemetry JS SDK 3 (`@opentelemetry/core` 3.x, `@opentelemetry/instrumentation` 0.301.x). `@opentelemetry/api` is now a peer dependency (`^1.10.0`), and Node.js 22.15.0 or newer is required.

**Breaking change:** apps that stay on OpenTelemetry SDK 2 (`@opentelemetry/api` < 1.10) must keep using `@bentocache/otel@0.1.x`.
2 changes: 2 additions & 0 deletions docs/content/docs/telemetry.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,8 @@ yarn add @bentocache/otel
```
:::

`@bentocache/otel` requires OpenTelemetry JS SDK 3 (`@opentelemetry/api` 1.10) and Node.js 22.15.0 or newer. For OpenTelemetry SDK 2, use `@bentocache/otel@0.1.x`.

## Basic setup

```ts
Expand Down
2 changes: 2 additions & 0 deletions packages/otel/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ Official OpenTelemetry instrumentation for Bentocache.
pnpm add @bentocache/otel
```

Requires OpenTelemetry JS SDK 3 (`@opentelemetry/api` 1.10) and Node.js 22.15.0 or newer. For OpenTelemetry SDK 2, use `@bentocache/otel@0.1.x`.

## Usage

```ts
Expand Down
13 changes: 9 additions & 4 deletions packages/otel/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,18 @@
"checks": "pnpm lint && pnpm typecheck"
},
"dependencies": {
"@opentelemetry/api": "^1.9.1",
"@opentelemetry/core": "^2.12.0",
"@opentelemetry/instrumentation": "^0.223.0"
"@opentelemetry/core": "^3.1.1",
"@opentelemetry/instrumentation": "^0.301.1"
},
"devDependencies": {
"@julr/utils": "^1.9.0",
"@opentelemetry/sdk-trace-base": "^2.12.0",
"@opentelemetry/api": "^1.10.0",
"@opentelemetry/context-async-hooks": "^3.1.1",
"@opentelemetry/sdk-trace": "^3.1.1",
"bentocache": "workspace:*"
},
"peerDependencies": {
"@opentelemetry/api": "^1.10.0",
"bentocache": "^1.6.0"
},
"c8": {
Expand All @@ -59,6 +61,9 @@
"html"
]
},
"engines": {
"node": ">=22.15.0"
},
"release-it": {
"git": {
"commitMessage": "chore(release): @bentocache/otel@${version}",
Expand Down
56 changes: 25 additions & 31 deletions packages/otel/src/instrumentation.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import { suppressTracing } from '@opentelemetry/core'
import type { Context, Span } from '@opentelemetry/api'
import type { CacheOperationMessage } from 'bentocache'
import type { ContextManagementToken, Span } from '@opentelemetry/api'
import type { TracingChannelSubscribers } from 'node:diagnostics_channel'
import { context, SpanKind, SpanStatusCode, trace } from '@opentelemetry/api'
import {
InstrumentationBase,
InstrumentationNodeModuleDefinition,
} from '@opentelemetry/instrumentation'

import packageJson from '../package.json' with { type: 'json' }
import type {
BentoCacheInstrumentationConfig,
BentoCacheModuleExports,
Expand All @@ -32,10 +33,11 @@ export class BentoCacheInstrumentation extends InstrumentationBase<BentoCacheIns
protected handlers?: TracingChannelSubscribers<CacheOperationMessage>

/**
* Tracks active getOrSet contexts so child operations (factory, set)
* can be parented to the getOrSet span. Keyed by `store:key`.
* Context tokens attached on `start` and disposed on the synchronous `end`
* event, so the operation span is the active context for everything the
* operation runs: nested cache operations and the user factory.
*/
#activeContexts = new Map<string, Context>()
#contextTokens = new WeakMap<object, ContextManagementToken>()
#cacheOperation?: CacheOperationChannel
#originalBentoCache?: BentoCacheModuleExports['BentoCache']

Expand Down Expand Up @@ -81,7 +83,10 @@ export class BentoCacheInstrumentation extends InstrumentationBase<BentoCacheIns
try {
moduleExports.BentoCache = BentoCachePatched
} catch {
return
this._diag.warn(
'Cannot patch the BentoCache constructor because the module exports are read-only (ESM namespace). ' +
'suppressInternalOperations has no effect on caches created from these exports.',
)
}
}

Expand Down Expand Up @@ -128,7 +133,7 @@ export class BentoCacheInstrumentation extends InstrumentationBase<BentoCacheIns
this.subscribed = true
this.handlers = {
start: message => this.#handleStart(message),
end: () => {},
end: message => this.#handleEnd(message),
asyncStart: () => {},
asyncEnd: message => this.#handleAsyncEnd(message),
error: message => this.#handleError(message),
Expand All @@ -148,26 +153,17 @@ export class BentoCacheInstrumentation extends InstrumentationBase<BentoCacheIns
this.subscribed = false
this.handlers = undefined
this.spans = new WeakMap()
this.#activeContexts.clear()
}

/**
* Starts a span for each cache operation event and tracks getOrSet parent contexts.
* Starts a span for each cache operation and makes it the active context
* while the operation runs, so nested operations and the factory are parented to it.
*/
#handleStart(message: CacheOperationMessage) {
const config = this.getConfig()
const contextKey = `${message.store}:${message.key}`
const parentContext = context.active()

// Only child operations (factory, set) use the active getOrSet context as parent.
// getOrSet operations themselves always use the current context to avoid
// chaining concurrent getOrSet calls for the same key into a nested hierarchy.
const isGetOrSet = message.operation === 'getOrSet'
const parentContext = !isGetOrSet
? (this.#activeContexts.get(contextKey) ?? context.active())
: context.active()
const parentSpan = trace.getSpan(parentContext)

if (config.requireParentSpan && !parentSpan) return
if (config.requireParentSpan && !trace.getSpan(parentContext)) return

const spanName = this.#getSpanName(message)
const span = this.tracer.startSpan(
Expand All @@ -180,10 +176,16 @@ export class BentoCacheInstrumentation extends InstrumentationBase<BentoCacheIns
)

this.spans.set(message, span)
this.#contextTokens.set(message, context.attach(trace.setSpan(parentContext, span)))
}

if (isGetOrSet) {
this.#activeContexts.set(contextKey, trace.setSpan(context.active(), span))
}
/**
* Restores the caller context once the operation has returned its promise.
* Async continuations created by the operation keep the attached context.
*/
#handleEnd(message: CacheOperationMessage) {
this.#contextTokens.get(message)?.dispose()
this.#contextTokens.delete(message)
}

/**
Expand All @@ -199,10 +201,6 @@ export class BentoCacheInstrumentation extends InstrumentationBase<BentoCacheIns

span.end()
this.spans.delete(message)

if (message.operation === 'getOrSet') {
this.#activeContexts.delete(`${message.store}:${message.key}`)
}
}

/**
Expand All @@ -219,10 +217,6 @@ export class BentoCacheInstrumentation extends InstrumentationBase<BentoCacheIns

span.end()
this.spans.delete(message)

if (message.operation === 'getOrSet') {
this.#activeContexts.delete(`${message.store}:${message.key}`)
}
}

/**
Expand Down Expand Up @@ -271,7 +265,7 @@ export class BentoCacheInstrumentation extends InstrumentationBase<BentoCacheIns
* Creates a new instrumentation instance with default and user config merged.
*/
constructor(config: BentoCacheInstrumentationConfig = {}) {
super('@bentocache/otel', '0.1.0', { ...DEFAULT_CONFIG, ...config })
super(packageJson.name, packageJson.version, { ...DEFAULT_CONFIG, ...config })
}

/**
Expand Down
20 changes: 10 additions & 10 deletions packages/otel/tests/helpers.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,7 @@
import { trace } from '@opentelemetry/api'
import { context, trace } from '@opentelemetry/api'
import { memoryDriver } from 'bentocache/drivers/memory'
import {
BasicTracerProvider,
InMemorySpanExporter,
SimpleSpanProcessor,
} from '@opentelemetry/sdk-trace-base'
import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks'
import { InMemorySpanExporter, SimpleSpanProcessor, TracerProvider } from '@opentelemetry/sdk-trace'

import { BentoCacheInstrumentation } from '../src/instrumentation.js'

Expand All @@ -21,7 +18,7 @@ type CleanupFn = (callback: () => Promise<void> | void) => void
/**
* Reused tracer setup shared across tests.
*/
let tracerSetup: { exporter: InMemorySpanExporter; provider: BasicTracerProvider } | undefined
let tracerSetup: { exporter: InMemorySpanExporter; provider: TracerProvider } | undefined

/**
* Creates a singleton tracer provider and in-memory exporter for the suite.
Expand All @@ -34,11 +31,12 @@ const setupTracer = () => {
}

const exporter = new InMemorySpanExporter()
const provider = new BasicTracerProvider({
spanProcessors: [new SimpleSpanProcessor(exporter)],
const provider = new TracerProvider({
spanProcessors: [new SimpleSpanProcessor({ exporter })],
})

trace.setGlobalTracerProvider(provider)
context.setGlobalContextManager(new AsyncLocalStorageContextManager().enable())

tracerSetup = { exporter, provider }
return tracerSetup
Expand All @@ -60,9 +58,11 @@ export const setupInstrumentation = async (
const moduleDefinitions = (instrumentation as any)._modules as any[]
const moduleDefinition = moduleDefinitions[0]

const bentocacheModule = await import('bentocache')
let bentocacheModule: any = await import('bentocache')

if (mode === 'modulePatch') {
// import-in-the-middle hands instrumentations a mutable view of the ESM namespace
bentocacheModule = { ...bentocacheModule }
moduleDefinition.patch?.(bentocacheModule)
instrumentation.enable()
} else {
Expand Down
Loading
Loading