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
12 changes: 11 additions & 1 deletion handwritten/spanner/src/instrument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
context,
trace,
INVALID_SPAN_CONTEXT,
ROOT_CONTEXT,

Check warning on line 29 in handwritten/spanner/src/instrument.ts

View workflow job for this annotation

GitHub Actions / lint

'ROOT_CONTEXT' is defined but never used
SpanAttributes,
TimeInput,
TracerProvider,
Expand Down Expand Up @@ -115,7 +115,7 @@
return {};
}

const SPAN_NAMESPACE_PREFIX = 'CloudSpanner'; // TODO: discuss & standardize this prefix.
const SPAN_NAMESPACE_PREFIX = 'CloudSpanner'; // TODO(https://github.com/googleapis/google-cloud-node/issues/9610): discuss & standardize this prefix.
export {
SPAN_NAMESPACE_PREFIX,
traceConfig,
Expand Down Expand Up @@ -145,6 +145,15 @@
* was called.
*/
function ensureInitialContextManagerSet() {
const currentContextManager = (
context as unknown as {_getContextManager?: () => ContextManager}
)._getContextManager?.();
if (
currentContextManager &&
currentContextManager.constructor?.name !== 'NoopContextManager'
) {
return;
}
if (!defaultContextManager) {
const ContextManagerClass =
AsyncLocalStorageContextManager || AsyncHooksContextManager;
Expand All @@ -169,6 +178,7 @@
*/
function isGlobalTracingEnabled(): boolean {
if (globalTracingEnabled === true) {
ensureInitialContextManagerSet();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Generated] Call ensureInitialContextManagerSet() inside the cached globalTracingEnabled === true fast path of _checkIfOpenTelemetryTracingIsEnabled() so that if context.disable() was invoked between tracing checks (e.g., in test teardowns), AsyncLocalStorageContextManager is re-registered under Bun and Node.js.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Calling ensureInitialContextManagerSet() on the cached if (globalTracingEnabled === true) fast path invokes context.setGlobalContextManager(defaultContextManager!) on every startTrace() and Spanner.request() call.

setGlobalContextManager calls registerGlobal('context', ...), and it constructs a new Error().stack and logs via diag.error on every call.

We can update ensureInitialContextManagerSet() to check context._getContextManager?.() first (which returns NoopContextManager only when uninitialized or after context.disable()):

function ensureInitialContextManagerSet() {
  const currentContextManager = (
    context as unknown as {_getContextManager?: () => ContextManager}
  )._getContextManager?.();
  if (
    currentContextManager &&
    currentContextManager.constructor?.name !== 'NoopContextManager'
  ) {
    return;
  }
  if (!defaultContextManager) {
    const ContextManagerClass =
      AsyncLocalStorageContextManager || AsyncHooksContextManager;
    defaultContextManager = new ContextManagerClass();
  }
  if (context.setGlobalContextManager(defaultContextManager!)) {
    defaultContextManager!.enable();
  }
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Great catch, thank you! Updated ensureInitialContextManagerSet() in a868341 to return early via context._getContextManager?.() when a non-NoopContextManager is already registered, and added a unit test verifying that repeated calls on the cached path do not invoke context.setGlobalContextManager() or log via diag.error.

return true;
}
const now = Date.now();
Expand All @@ -183,8 +193,8 @@
const globalProvider = trace.getTracerProvider();
if (globalProvider) {
let delegate = globalProvider;
if (typeof (globalProvider as any).getDelegate === 'function') {

Check warning on line 196 in handwritten/spanner/src/instrument.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
delegate = (globalProvider as any).getDelegate();

Check warning on line 197 in handwritten/spanner/src/instrument.ts

View workflow job for this annotation

GitHub Actions / lint

Unexpected any. Specify a different type
}
if (delegate) {
const name = delegate.constructor.name;
Expand Down Expand Up @@ -374,23 +384,23 @@
return INVALID_SPAN_CONTEXT;
}

setAttribute(key: string, value: unknown): this {

Check warning on line 387 in handwritten/spanner/src/instrument.ts

View workflow job for this annotation

GitHub Actions / lint

'value' is defined but never used

Check warning on line 387 in handwritten/spanner/src/instrument.ts

View workflow job for this annotation

GitHub Actions / lint

'key' is defined but never used
return this;
}

setAttributes(attributes: SpanAttributes): this {

Check warning on line 391 in handwritten/spanner/src/instrument.ts

View workflow job for this annotation

GitHub Actions / lint

'attributes' is defined but never used
return this;
}

addEvent(name: string, attributes?: SpanAttributes): this {

Check warning on line 395 in handwritten/spanner/src/instrument.ts

View workflow job for this annotation

GitHub Actions / lint

'attributes' is defined but never used

Check warning on line 395 in handwritten/spanner/src/instrument.ts

View workflow job for this annotation

GitHub Actions / lint

'name' is defined but never used
return this;
}

addLink(link: Link): this {

Check warning on line 399 in handwritten/spanner/src/instrument.ts

View workflow job for this annotation

GitHub Actions / lint

'link' is defined but never used
return this;
}

addLinks(links: Link[]): this {

Check warning on line 403 in handwritten/spanner/src/instrument.ts

View workflow job for this annotation

GitHub Actions / lint

'links' is defined but never used
return this;
}

Expand Down
162 changes: 146 additions & 16 deletions handwritten/spanner/test/instrument.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@
*/

import * as assert from 'assert';
import {context} from '@opentelemetry/api';
import {Span, TracerProvider, context, diag, trace} from '@opentelemetry/api';
import {describe, it} from 'mocha';
import * as sinon from 'sinon';
import {
_resetTracingEnabledForTest,
ensureInitialContextManagerSet,
getActiveOrNoopSpan,
getQueryTraceConfig,
Expand Down Expand Up @@ -115,40 +117,168 @@ describe('instrument', () => {
setAttribute: () => fakeSpan,
setAttributes: () => fakeSpan,
addEvent: () => fakeSpan,
addLink: () => fakeSpan,
addLinks: () => fakeSpan,
setStatus: () => fakeSpan,
updateName: () => fakeSpan,
end: () => {},
isRecording: () => true,
recordException: () => {},
};
return context.with(traceSetSpan(context.active(), fakeSpan), () =>
return context.with(trace.setSpan(context.active(), fakeSpan), () =>
fn(fakeSpan),
);
},
}),
};

const {trace} = require('@opentelemetry/api');
function traceSetSpan(ctx: unknown, span: unknown) {
return trace.setSpan(ctx, span);
try {
let activeSpanAfterAwait: Span | undefined;
await startTrace(
'Test.asyncSpan',
{
opts: {
tracerProvider: fakeTracerProvider as unknown as TracerProvider,
},
},
async span => {
await Promise.resolve();
activeSpanAfterAwait = getActiveOrNoopSpan();
span.end();
},
);

assert.strictEqual(
activeSpanAfterAwait?.spanContext().spanId,
'2'.repeat(16),
);
} finally {
ensureInitialContextManagerSet();
}
});

let activeSpanAfterAwait: unknown;
await startTrace(
'Test.asyncSpan',
{opts: {tracerProvider: fakeTracerProvider as any}},
async span => {
it('should re-enable context manager on cached global tracing check after context.disable()', async () => {
const fakeTracerProvider = {
getTracer: () => ({
startActiveSpan: (
_name: string,
_opts: unknown,
fn: (span: unknown) => unknown,
) => {
const fakeSpan = {
spanContext: () => ({
traceId: '3'.repeat(32),
spanId: '4'.repeat(16),
traceFlags: 1,
}),
setAttribute: () => fakeSpan,
setAttributes: () => fakeSpan,
addEvent: () => fakeSpan,
addLink: () => fakeSpan,
addLinks: () => fakeSpan,
setStatus: () => fakeSpan,
updateName: () => fakeSpan,
end: () => {},
isRecording: () => true,
recordException: () => {},
};
return context.with(trace.setSpan(context.active(), fakeSpan), () =>
fn(fakeSpan),
);
},
}),
};

_resetTracingEnabledForTest();
const getTracerProviderStub = sinon
.stub(trace, 'getTracerProvider')
.returns(fakeTracerProvider as unknown as TracerProvider);
try {
// First trace primes globalTracingEnabled = true
await startTrace('Test.primedSpan', undefined, async span => {
span.end();
});
// Disable context manager while globalTracingEnabled remains cached as true
context.disable();

let activeSpanAfterAwait: Span | undefined;
await startTrace('Test.cachedGlobalSpan', undefined, async span => {
await Promise.resolve();
activeSpanAfterAwait = getActiveOrNoopSpan();
span.end();
},
);
});

assert.strictEqual(
activeSpanAfterAwait?.spanContext().spanId,
'4'.repeat(16),
);
} finally {
getTracerProviderStub.restore();
_resetTracingEnabledForTest();
ensureInitialContextManagerSet();
}
});

it('should not call setGlobalContextManager or diag.error when a context manager is already registered', async () => {
const fakeTracerProvider = {
getTracer: () => ({
startActiveSpan: (
_name: string,
_opts: unknown,
fn: (span: unknown) => unknown,
) => {
const fakeSpan = {
spanContext: () => ({
traceId: '5'.repeat(32),
spanId: '6'.repeat(16),
traceFlags: 1,
}),
setAttribute: () => fakeSpan,
setAttributes: () => fakeSpan,
addEvent: () => fakeSpan,
addLink: () => fakeSpan,
addLinks: () => fakeSpan,
setStatus: () => fakeSpan,
updateName: () => fakeSpan,
end: () => {},
isRecording: () => true,
recordException: () => {},
};
return context.with(trace.setSpan(context.active(), fakeSpan), () =>
fn(fakeSpan),
);
},
}),
};

assert.strictEqual(
(activeSpanAfterAwait as any)?.spanContext?.().spanId,
'2'.repeat(16),
);
context.disable();
ensureInitialContextManagerSet();
_resetTracingEnabledForTest();

const sandbox = sinon.createSandbox();
const setGlobalSpy = sandbox.spy(context, 'setGlobalContextManager');
const diagErrorSpy = sandbox.spy(diag, 'error');
sandbox
.stub(trace, 'getTracerProvider')
.returns(fakeTracerProvider as unknown as TracerProvider);

try {
// First trace sets globalTracingEnabled = true; subsequent traces hit the cached fast path
await startTrace('Test.first', undefined, async span => {
span.end();
});
await startTrace('Test.second', undefined, async span => {
span.end();
});
ensureInitialContextManagerSet();

assert.strictEqual(setGlobalSpy.callCount, 0);
assert.strictEqual(diagErrorSpy.callCount, 0);
} finally {
sandbox.restore();
_resetTracingEnabledForTest();
ensureInitialContextManagerSet();
}
});

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Generated] Add unit test verifying that ensureInitialContextManagerSet re-registers AsyncLocalStorageContextManager on subsequent cached _checkIfOpenTelemetryTracingIsEnabled() calls after context.disable().

});
});
Loading