Merge pull request #34089 from backstage/otel/mcp-tools-call
feat: Instrument MCP tool calls with semantically appropriate span
This commit is contained in:
+165
-27
@@ -13,7 +13,13 @@
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
import { SpanKind, SpanStatusCode, trace } from '@opentelemetry/api';
|
||||
import {
|
||||
SpanKind,
|
||||
SpanStatusCode,
|
||||
context,
|
||||
propagation,
|
||||
trace,
|
||||
} from '@opentelemetry/api';
|
||||
import { mockCredentials, mockServices } from '@backstage/backend-test-utils';
|
||||
import { DefaultTracingService } from './DefaultTracingService';
|
||||
|
||||
@@ -88,10 +94,11 @@ describe('DefaultTracingService', () => {
|
||||
|
||||
it('passes name, kind, and caller attributes through to the tracer', async () => {
|
||||
const service = createService();
|
||||
await service.startActiveSpan('op', async () => undefined, {
|
||||
kind: 'server',
|
||||
attributes: { foo: 'bar' },
|
||||
});
|
||||
await service.startActiveSpan(
|
||||
'op',
|
||||
{ kind: 'server', attributes: { foo: 'bar' } },
|
||||
async () => undefined,
|
||||
);
|
||||
|
||||
expect(mocks.tracer.startActiveSpan).toHaveBeenCalledWith(
|
||||
'op',
|
||||
@@ -113,9 +120,11 @@ describe('DefaultTracingService', () => {
|
||||
|
||||
it('lets caller-supplied attributes override backstage.plugin.id at start time', async () => {
|
||||
const service = createService({ pluginId: 'my-plugin' });
|
||||
await service.startActiveSpan('op', async () => undefined, {
|
||||
attributes: { 'backstage.plugin.id': 'other-plugin' },
|
||||
});
|
||||
await service.startActiveSpan(
|
||||
'op',
|
||||
{ attributes: { 'backstage.plugin.id': 'other-plugin' } },
|
||||
async () => undefined,
|
||||
);
|
||||
|
||||
const attrs = mocks.tracer.startActiveSpan.mock.calls[0][1].attributes;
|
||||
expect(attrs['backstage.plugin.id']).toBe('other-plugin');
|
||||
@@ -140,18 +149,22 @@ describe('DefaultTracingService', () => {
|
||||
];
|
||||
for (const [kind, expected] of cases) {
|
||||
mocks.tracer.startActiveSpan.mockClear();
|
||||
await service.startActiveSpan('op', async () => undefined, {
|
||||
kind: kind as any,
|
||||
});
|
||||
await service.startActiveSpan(
|
||||
'op',
|
||||
{ kind: kind as any },
|
||||
async () => undefined,
|
||||
);
|
||||
expect(mocks.tracer.startActiveSpan.mock.calls[0][1].kind).toBe(expected);
|
||||
}
|
||||
});
|
||||
|
||||
it('adds backstage.principal.type but not enduser.id when capture is off', async () => {
|
||||
const service = createService({ captureEndUser: false });
|
||||
await service.startActiveSpan('op', async () => undefined, {
|
||||
credentials: mockCredentials.user('user:default/alice'),
|
||||
});
|
||||
await service.startActiveSpan(
|
||||
'op',
|
||||
{ credentials: mockCredentials.user('user:default/alice') },
|
||||
async () => undefined,
|
||||
);
|
||||
|
||||
const attrs = mocks.tracer.startActiveSpan.mock.calls[0][1].attributes;
|
||||
expect(attrs['backstage.principal.type']).toBe('user');
|
||||
@@ -160,9 +173,11 @@ describe('DefaultTracingService', () => {
|
||||
|
||||
it('adds enduser.id from a user principal when capture is on', async () => {
|
||||
const service = createService({ captureEndUser: true });
|
||||
await service.startActiveSpan('op', async () => undefined, {
|
||||
credentials: mockCredentials.user('user:default/alice'),
|
||||
});
|
||||
await service.startActiveSpan(
|
||||
'op',
|
||||
{ credentials: mockCredentials.user('user:default/alice') },
|
||||
async () => undefined,
|
||||
);
|
||||
|
||||
const attrs = mocks.tracer.startActiveSpan.mock.calls[0][1].attributes;
|
||||
expect(attrs['enduser.id']).toBe('user:default/alice');
|
||||
@@ -170,9 +185,11 @@ describe('DefaultTracingService', () => {
|
||||
|
||||
it('adds enduser.id from a service principal subject when capture is on', async () => {
|
||||
const service = createService({ captureEndUser: true });
|
||||
await service.startActiveSpan('op', async () => undefined, {
|
||||
credentials: mockCredentials.service('plugin:test'),
|
||||
});
|
||||
await service.startActiveSpan(
|
||||
'op',
|
||||
{ credentials: mockCredentials.service('plugin:test') },
|
||||
async () => undefined,
|
||||
);
|
||||
|
||||
const attrs = mocks.tracer.startActiveSpan.mock.calls[0][1].attributes;
|
||||
expect(attrs['enduser.id']).toBe('plugin:test');
|
||||
@@ -189,9 +206,11 @@ describe('DefaultTracingService', () => {
|
||||
httpAuth,
|
||||
});
|
||||
|
||||
await service.startActiveSpan('op', async () => undefined, {
|
||||
request: { headers: {} } as any,
|
||||
});
|
||||
await service.startActiveSpan(
|
||||
'op',
|
||||
{ request: { headers: {} } as any },
|
||||
async () => undefined,
|
||||
);
|
||||
|
||||
expect(credSpy).toHaveBeenCalledTimes(1);
|
||||
const attrs = mocks.tracer.startActiveSpan.mock.calls[0][1].attributes;
|
||||
@@ -208,10 +227,14 @@ describe('DefaultTracingService', () => {
|
||||
httpAuth,
|
||||
});
|
||||
|
||||
await service.startActiveSpan('op', async () => undefined, {
|
||||
credentials: mockCredentials.user('user:default/explicit'),
|
||||
request: { headers: {} } as any,
|
||||
});
|
||||
await service.startActiveSpan(
|
||||
'op',
|
||||
{
|
||||
credentials: mockCredentials.user('user:default/explicit'),
|
||||
request: { headers: {} } as any,
|
||||
},
|
||||
async () => undefined,
|
||||
);
|
||||
|
||||
expect(credSpy).not.toHaveBeenCalled();
|
||||
const attrs = mocks.tracer.startActiveSpan.mock.calls[0][1].attributes;
|
||||
@@ -267,4 +290,119 @@ describe('DefaultTracingService', () => {
|
||||
expect(value).toBe(42);
|
||||
expect(mocks.span.end).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
describe('context', () => {
|
||||
describe('active', () => {
|
||||
it('returns the OTel active context as an opaque handle', () => {
|
||||
const fakeCtx = { __ctx: 'active' };
|
||||
jest.spyOn(context, 'active').mockReturnValue(fakeCtx as any);
|
||||
const service = createService();
|
||||
expect(service.context.active()).toBe(fakeCtx);
|
||||
});
|
||||
});
|
||||
|
||||
describe('with', () => {
|
||||
it('delegates to OTel context.with on the supplied handle and returns the fn result', async () => {
|
||||
const fakeCtx = { __ctx: 'extracted' } as any;
|
||||
const withSpy = jest
|
||||
.spyOn(context, 'with')
|
||||
.mockImplementation((_ctx, fn) => (fn as any)());
|
||||
|
||||
const service = createService();
|
||||
const result = await service.context.with(fakeCtx, () => 99);
|
||||
|
||||
expect(withSpy).toHaveBeenCalledWith(fakeCtx, expect.any(Function));
|
||||
expect(result).toBe(99);
|
||||
});
|
||||
|
||||
it('awaits an async fn and returns its resolved value', async () => {
|
||||
jest
|
||||
.spyOn(context, 'with')
|
||||
.mockImplementation((_ctx, fn) => (fn as any)());
|
||||
|
||||
const service = createService();
|
||||
const result = await service.context.with(
|
||||
{} as any,
|
||||
async () => 'async-val',
|
||||
);
|
||||
expect(result).toBe('async-val');
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('propagation', () => {
|
||||
describe('extract', () => {
|
||||
it('forwards the supplied context and headers to OTel propagation.extract', () => {
|
||||
const baseCtx = { __ctx: 'base' } as any;
|
||||
const extractedCtx = { __ctx: 'extracted' } as any;
|
||||
const extractSpy = jest
|
||||
.spyOn(propagation, 'extract')
|
||||
.mockReturnValue(extractedCtx);
|
||||
|
||||
const service = createService();
|
||||
const headers = { traceparent: '00-abc-def-01' };
|
||||
const result = service.propagation.extract(baseCtx, headers);
|
||||
|
||||
expect(extractSpy).toHaveBeenCalledWith(baseCtx, headers);
|
||||
expect(result).toBe(extractedCtx);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getActiveBaggage', () => {
|
||||
it('returns a read-only baggage wrapping the active context baggage', () => {
|
||||
const mockBaggage = {
|
||||
getAllEntries: jest.fn(() => [
|
||||
['gen_ai.conversation.id', { value: 'conv-1' }],
|
||||
['gen_ai.agent.id', { value: 'agent-2' }],
|
||||
]),
|
||||
getEntry: jest.fn(),
|
||||
setEntry: jest.fn(),
|
||||
removeEntry: jest.fn(),
|
||||
removeEntries: jest.fn(),
|
||||
clear: jest.fn(),
|
||||
};
|
||||
jest
|
||||
.spyOn(propagation, 'getActiveBaggage')
|
||||
.mockReturnValue(mockBaggage as any);
|
||||
|
||||
const service = createService();
|
||||
const baggage = service.propagation.getActiveBaggage();
|
||||
|
||||
expect(baggage).toBeDefined();
|
||||
expect(baggage!.getAllEntries()).toEqual([
|
||||
['gen_ai.conversation.id', { value: 'conv-1' }],
|
||||
['gen_ai.agent.id', { value: 'agent-2' }],
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getBaggage', () => {
|
||||
it('returns baggage from the supplied context', () => {
|
||||
const ctx = { __ctx: 'has-baggage' } as any;
|
||||
const mockBaggage = {
|
||||
getAllEntries: jest.fn(() => [['k', { value: 'ctx-val' }]]),
|
||||
getEntry: jest.fn(),
|
||||
setEntry: jest.fn(),
|
||||
removeEntry: jest.fn(),
|
||||
removeEntries: jest.fn(),
|
||||
clear: jest.fn(),
|
||||
};
|
||||
const getBaggageSpy = jest
|
||||
.spyOn(propagation, 'getBaggage')
|
||||
.mockReturnValue(mockBaggage as any);
|
||||
|
||||
const service = createService();
|
||||
const baggage = service.propagation.getBaggage(ctx);
|
||||
|
||||
expect(getBaggageSpy).toHaveBeenCalledWith(ctx);
|
||||
expect(baggage!.getAllEntries()).toEqual([['k', { value: 'ctx-val' }]]);
|
||||
});
|
||||
|
||||
it('returns undefined when the context has no baggage', () => {
|
||||
jest.spyOn(propagation, 'getBaggage').mockReturnValue(undefined);
|
||||
const service = createService();
|
||||
expect(service.propagation.getBaggage({} as any)).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -14,7 +14,15 @@
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { SpanKind, SpanStatusCode, Tracer, trace } from '@opentelemetry/api';
|
||||
import {
|
||||
Context,
|
||||
SpanKind,
|
||||
SpanStatusCode,
|
||||
Tracer,
|
||||
context as otelContext,
|
||||
propagation as otelPropagation,
|
||||
trace,
|
||||
} from '@opentelemetry/api';
|
||||
import {
|
||||
BackstageCredentials,
|
||||
HttpAuthService,
|
||||
@@ -22,6 +30,10 @@ import {
|
||||
import {
|
||||
TracingService,
|
||||
TracingServiceAttributes,
|
||||
TracingServiceBaggage,
|
||||
TracingServiceContext,
|
||||
TracingServiceContextAPI,
|
||||
TracingServicePropagationAPI,
|
||||
TracingServiceSpan,
|
||||
TracingServiceSpanKind,
|
||||
TracingServiceSpanOptions,
|
||||
@@ -42,6 +54,28 @@ export interface DefaultTracingServiceOptions {
|
||||
httpAuth: HttpAuthService;
|
||||
}
|
||||
|
||||
// `TracingServiceContext` is an opaque handle for an OTel `Context`. Internally
|
||||
// the value *is* the OTel context; we just narrow the type so consumers can't
|
||||
// poke at it directly.
|
||||
function toOtelContext(ctx: TracingServiceContext): Context {
|
||||
return ctx as unknown as Context;
|
||||
}
|
||||
function fromOtelContext(ctx: Context): TracingServiceContext {
|
||||
return ctx as unknown as TracingServiceContext;
|
||||
}
|
||||
|
||||
function wrapOtelBaggage(
|
||||
baggage: ReturnType<typeof otelPropagation.getActiveBaggage>,
|
||||
): TracingServiceBaggage | undefined {
|
||||
if (!baggage) return undefined;
|
||||
return {
|
||||
getAllEntries: () =>
|
||||
baggage
|
||||
.getAllEntries()
|
||||
.map(([key, entry]) => [key, { value: entry.value }]),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Default implementation of the {@link TracingService} interface.
|
||||
*
|
||||
@@ -53,6 +87,32 @@ export class DefaultTracingService implements TracingService {
|
||||
private readonly captureEndUser: boolean;
|
||||
private readonly httpAuth: HttpAuthService;
|
||||
|
||||
readonly context: TracingServiceContextAPI = {
|
||||
active: () => fromOtelContext(otelContext.active()),
|
||||
// `otelContext.with` is synchronous: it activates `ctx`, invokes `fn`,
|
||||
// then restores the previous active context before this call returns.
|
||||
// When `fn` is async, the AsyncLocalStorage context manager installed
|
||||
// by the OTel SDK is what keeps `ctx` active across the callback's
|
||||
// `await`s. If no context manager is registered (e.g. in a test that
|
||||
// does not wire up the OTel SDK) the `await` continuations will run
|
||||
// outside `ctx`.
|
||||
with: async <T>(
|
||||
ctx: TracingServiceContext,
|
||||
fn: () => T | Promise<T>,
|
||||
): Promise<T> => otelContext.with(toOtelContext(ctx), fn),
|
||||
};
|
||||
|
||||
readonly propagation: TracingServicePropagationAPI = {
|
||||
extract: (
|
||||
ctx: TracingServiceContext,
|
||||
carrier: Record<string, string | string[] | undefined>,
|
||||
): TracingServiceContext =>
|
||||
fromOtelContext(otelPropagation.extract(toOtelContext(ctx), carrier)),
|
||||
getBaggage: (ctx: TracingServiceContext) =>
|
||||
wrapOtelBaggage(otelPropagation.getBaggage(toOtelContext(ctx))),
|
||||
getActiveBaggage: () => wrapOtelBaggage(otelPropagation.getActiveBaggage()),
|
||||
};
|
||||
|
||||
private constructor(opts: DefaultTracingServiceOptions) {
|
||||
this.tracer = trace
|
||||
.getTracerProvider()
|
||||
@@ -66,11 +126,30 @@ export class DefaultTracingService implements TracingService {
|
||||
return new DefaultTracingService(opts);
|
||||
}
|
||||
|
||||
async startActiveSpan<T>(
|
||||
startActiveSpan<T>(
|
||||
name: string,
|
||||
fn: (span: TracingServiceSpan) => T | Promise<T>,
|
||||
options: TracingServiceSpanOptions = {},
|
||||
): Promise<T>;
|
||||
startActiveSpan<T>(
|
||||
name: string,
|
||||
options: TracingServiceSpanOptions,
|
||||
fn: (span: TracingServiceSpan) => T | Promise<T>,
|
||||
): Promise<T>;
|
||||
async startActiveSpan<T>(
|
||||
name: string,
|
||||
optionsOrFn:
|
||||
| TracingServiceSpanOptions
|
||||
| ((span: TracingServiceSpan) => T | Promise<T>),
|
||||
maybeFn?: (span: TracingServiceSpan) => T | Promise<T>,
|
||||
): Promise<T> {
|
||||
const [options, fn]: [
|
||||
TracingServiceSpanOptions,
|
||||
(span: TracingServiceSpan) => T | Promise<T>,
|
||||
] =
|
||||
typeof optionsOrFn === 'function'
|
||||
? [{}, optionsOrFn]
|
||||
: [optionsOrFn, maybeFn!];
|
||||
|
||||
let credentials = options.credentials;
|
||||
if (!credentials && options.request) {
|
||||
credentials = await this.httpAuth.credentials(options.request);
|
||||
|
||||
@@ -292,10 +292,16 @@ export const rootSystemMetadataServiceRef: ServiceRef<
|
||||
|
||||
// @alpha
|
||||
export interface TracingService {
|
||||
readonly context: TracingServiceContextAPI;
|
||||
readonly propagation: TracingServicePropagationAPI;
|
||||
startActiveSpan<T>(
|
||||
name: string,
|
||||
fn: (span: TracingServiceSpan) => T | Promise<T>,
|
||||
options?: TracingServiceSpanOptions,
|
||||
): Promise<T>;
|
||||
startActiveSpan<T>(
|
||||
name: string,
|
||||
options: TracingServiceSpanOptions,
|
||||
fn: (span: TracingServiceSpan) => T | Promise<T>,
|
||||
): Promise<T>;
|
||||
}
|
||||
|
||||
@@ -314,6 +320,40 @@ export type TracingServiceAttributeValue =
|
||||
| Array<null | undefined | number>
|
||||
| Array<null | undefined | boolean>;
|
||||
|
||||
// @alpha
|
||||
export interface TracingServiceBaggage {
|
||||
// (undocumented)
|
||||
getAllEntries(): Array<[string, TracingServiceBaggageEntry]>;
|
||||
}
|
||||
|
||||
// @alpha
|
||||
export interface TracingServiceBaggageEntry {
|
||||
// (undocumented)
|
||||
value: string;
|
||||
}
|
||||
|
||||
// @alpha
|
||||
export interface TracingServiceContext {
|
||||
// (undocumented)
|
||||
readonly $$type: '@backstage/TracingServiceContext';
|
||||
}
|
||||
|
||||
// @alpha
|
||||
export interface TracingServiceContextAPI {
|
||||
active(): TracingServiceContext;
|
||||
with<T>(context: TracingServiceContext, fn: () => T | Promise<T>): Promise<T>;
|
||||
}
|
||||
|
||||
// @alpha
|
||||
export interface TracingServicePropagationAPI {
|
||||
extract(
|
||||
context: TracingServiceContext,
|
||||
carrier: Record<string, string | string[] | undefined>,
|
||||
): TracingServiceContext;
|
||||
getActiveBaggage(): TracingServiceBaggage | undefined;
|
||||
getBaggage(context: TracingServiceContext): TracingServiceBaggage | undefined;
|
||||
}
|
||||
|
||||
// @alpha
|
||||
export const tracingServiceRef: ServiceRef<
|
||||
TracingService,
|
||||
|
||||
@@ -104,6 +104,104 @@ export interface TracingService {
|
||||
startActiveSpan<T>(
|
||||
name: string,
|
||||
fn: (span: TracingServiceSpan) => T | Promise<T>,
|
||||
options?: TracingServiceSpanOptions,
|
||||
): Promise<T>;
|
||||
/**
|
||||
* Runs `fn` inside a new active span configured by `options`. The
|
||||
* span is finished when `fn` resolves or throws.
|
||||
*/
|
||||
startActiveSpan<T>(
|
||||
name: string,
|
||||
options: TracingServiceSpanOptions,
|
||||
fn: (span: TracingServiceSpan) => T | Promise<T>,
|
||||
): Promise<T>;
|
||||
|
||||
/**
|
||||
* Read the active tracing context, or run work within a specific
|
||||
* one.
|
||||
*/
|
||||
readonly context: TracingServiceContextAPI;
|
||||
|
||||
/**
|
||||
* Extract a caller's tracing context from an inbound carrier, and
|
||||
* read baggage from a context. Use these to bridge context across
|
||||
* boundaries where automatic propagation is lost — for example,
|
||||
* when a request arrives over a transport that does not
|
||||
* automatically attach the caller's context.
|
||||
*/
|
||||
readonly propagation: TracingServicePropagationAPI;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the active tracing context, or run work within a specific one.
|
||||
* The context carries the active span and propagation fields (trace
|
||||
* parent, baggage) for the current unit of work, and is automatically
|
||||
* inherited by spans created via `startActiveSpan`.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
export interface TracingServiceContextAPI {
|
||||
/** Returns the currently active context. */
|
||||
active(): TracingServiceContext;
|
||||
/** Runs `fn` with the supplied context set as the active context. */
|
||||
with<T>(context: TracingServiceContext, fn: () => T | Promise<T>): Promise<T>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract a caller's trace parent and baggage from an inbound carrier
|
||||
* (typically HTTP headers), or read baggage from a context. Use these
|
||||
* to bridge context across boundaries where automatic propagation is
|
||||
* lost.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
export interface TracingServicePropagationAPI {
|
||||
/**
|
||||
* Returns a new context with propagation fields (trace parent,
|
||||
* baggage, ...) read from the supplied carrier merged into it.
|
||||
*/
|
||||
extract(
|
||||
context: TracingServiceContext,
|
||||
carrier: Record<string, string | string[] | undefined>,
|
||||
): TracingServiceContext;
|
||||
/**
|
||||
* Returns the baggage attached to the supplied context, or
|
||||
* `undefined` when none is present.
|
||||
*/
|
||||
getBaggage(context: TracingServiceContext): TracingServiceBaggage | undefined;
|
||||
/**
|
||||
* Returns the baggage attached to the currently active context, or
|
||||
* `undefined` when none is present. Equivalent to
|
||||
* `getBaggage(context.active())`.
|
||||
*/
|
||||
getActiveBaggage(): TracingServiceBaggage | undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Opaque handle representing a tracing context. Consumers receive
|
||||
* these from {@link TracingServiceContextAPI.active} or
|
||||
* {@link TracingServicePropagationAPI.extract} and pass them back into
|
||||
* the API; the type carries no inspectable fields.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
export interface TracingServiceContext {
|
||||
readonly $$type: '@backstage/TracingServiceContext';
|
||||
}
|
||||
|
||||
/**
|
||||
* A read-only view of propagated baggage entries.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
export interface TracingServiceBaggage {
|
||||
getAllEntries(): Array<[string, TracingServiceBaggageEntry]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* A single baggage entry.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
export interface TracingServiceBaggageEntry {
|
||||
value: string;
|
||||
}
|
||||
|
||||
@@ -50,6 +50,11 @@ export type {
|
||||
TracingService,
|
||||
TracingServiceAttributeValue,
|
||||
TracingServiceAttributes,
|
||||
TracingServiceBaggage,
|
||||
TracingServiceBaggageEntry,
|
||||
TracingServiceContext,
|
||||
TracingServiceContextAPI,
|
||||
TracingServicePropagationAPI,
|
||||
TracingServiceSpan,
|
||||
TracingServiceSpanKind,
|
||||
TracingServiceSpanOptions,
|
||||
|
||||
@@ -71,7 +71,7 @@ export const metricsServiceRef = createServiceRef<
|
||||
/**
|
||||
* Service for managing trace spans.
|
||||
*
|
||||
* See {@link TracingService} for the API surface.
|
||||
* See `TracingService` for the API surface.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
|
||||
@@ -16,6 +16,8 @@ import { MetricsService } from '@backstage/backend-plugin-api/alpha';
|
||||
import { ServiceFactory } from '@backstage/backend-plugin-api';
|
||||
import { TracingService } from '@backstage/backend-plugin-api/alpha';
|
||||
import { TracingServiceAttributeValue } from '@backstage/backend-plugin-api/alpha';
|
||||
import { TracingServiceContextAPI } from '@backstage/backend-plugin-api/alpha';
|
||||
import { TracingServicePropagationAPI } from '@backstage/backend-plugin-api/alpha';
|
||||
import { TracingServiceSpan } from '@backstage/backend-plugin-api/alpha';
|
||||
import { TracingServiceSpanStatus } from '@backstage/backend-plugin-api/alpha';
|
||||
|
||||
@@ -85,6 +87,28 @@ export class MockActionsRegistry
|
||||
>(options: ActionsRegistryActionOptions<TInputSchema, TOutputSchema>): void;
|
||||
}
|
||||
|
||||
// @alpha
|
||||
export interface MockedTracingServiceContextAPI
|
||||
extends TracingServiceContextAPI {
|
||||
// (undocumented)
|
||||
active: jest.MockedFunction<TracingServiceContextAPI['active']>;
|
||||
// (undocumented)
|
||||
with: jest.MockedFunction<TracingServiceContextAPI['with']>;
|
||||
}
|
||||
|
||||
// @alpha
|
||||
export interface MockedTracingServicePropagationAPI
|
||||
extends TracingServicePropagationAPI {
|
||||
// (undocumented)
|
||||
extract: jest.MockedFunction<TracingServicePropagationAPI['extract']>;
|
||||
// (undocumented)
|
||||
getActiveBaggage: jest.MockedFunction<
|
||||
TracingServicePropagationAPI['getActiveBaggage']
|
||||
>;
|
||||
// (undocumented)
|
||||
getBaggage: jest.MockedFunction<TracingServicePropagationAPI['getBaggage']>;
|
||||
}
|
||||
|
||||
// @alpha
|
||||
export interface MockedTracingServiceSpan extends TracingServiceSpan {
|
||||
// (undocumented)
|
||||
@@ -106,8 +130,12 @@ export type ServiceMock<TService> = {
|
||||
|
||||
// @alpha
|
||||
export interface TracingServiceMock extends TracingService {
|
||||
// (undocumented)
|
||||
context: MockedTracingServiceContextAPI;
|
||||
// (undocumented)
|
||||
factory: ServiceFactory<TracingService>;
|
||||
// (undocumented)
|
||||
propagation: MockedTracingServicePropagationAPI;
|
||||
spans: MockedTracingServiceSpan[];
|
||||
// (undocumented)
|
||||
startActiveSpan: jest.MockedFunction<TracingService['startActiveSpan']>;
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
/*
|
||||
* Copyright 2026 The Backstage Authors
|
||||
*
|
||||
* Licensed under the Apache License, Version 2.0 (the "License");
|
||||
* you may not use this file except in compliance with the License.
|
||||
* You may obtain a copy of the License at
|
||||
*
|
||||
* http://www.apache.org/licenses/LICENSE-2.0
|
||||
*
|
||||
* Unless required by applicable law or agreed to in writing, software
|
||||
* distributed under the License is distributed on an "AS IS" BASIS,
|
||||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
* See the License for the specific language governing permissions and
|
||||
* limitations under the License.
|
||||
*/
|
||||
|
||||
import { tracingServiceMock } from './TracingServiceMock';
|
||||
|
||||
describe('tracingServiceMock', () => {
|
||||
it('parses the baggage header via propagation.extract and exposes it via getActiveBaggage inside context.with', async () => {
|
||||
const tracing = tracingServiceMock.mock();
|
||||
|
||||
const ctx = tracing.propagation.extract(tracing.context.active(), {
|
||||
baggage:
|
||||
'gen_ai.conversation.id=conv-123, gen_ai.agent.id=agent-456;property=ignored',
|
||||
});
|
||||
|
||||
// Baggage is reachable directly off the extracted handle.
|
||||
expect(tracing.propagation.getBaggage(ctx)?.getAllEntries()).toEqual([
|
||||
['gen_ai.conversation.id', { value: 'conv-123' }],
|
||||
['gen_ai.agent.id', { value: 'agent-456' }],
|
||||
]);
|
||||
|
||||
const seen = await tracing.context.with(ctx, () =>
|
||||
tracing.propagation
|
||||
.getActiveBaggage()
|
||||
?.getAllEntries()
|
||||
.map(([k, v]) => [k, v.value]),
|
||||
);
|
||||
|
||||
expect(seen).toEqual([
|
||||
['gen_ai.conversation.id', 'conv-123'],
|
||||
['gen_ai.agent.id', 'agent-456'],
|
||||
]);
|
||||
|
||||
// Baggage is scoped to the context.with callback.
|
||||
expect(tracing.propagation.getActiveBaggage()).toBeUndefined();
|
||||
});
|
||||
|
||||
it('honours mockReturnValue overrides for getActiveBaggage', async () => {
|
||||
const tracing = tracingServiceMock.mock();
|
||||
const override = {
|
||||
getAllEntries: () =>
|
||||
[['gen_ai.conversation.id', { value: 'override' }]] as Array<
|
||||
[string, { value: string }]
|
||||
>,
|
||||
};
|
||||
tracing.propagation.getActiveBaggage.mockReturnValue(override);
|
||||
|
||||
expect(tracing.propagation.getActiveBaggage()).toBe(override);
|
||||
const ctx = tracing.propagation.extract(tracing.context.active(), {
|
||||
baggage: 'gen_ai.conversation.id=conv-from-header',
|
||||
});
|
||||
await tracing.context.with(ctx, () => {
|
||||
// mockReturnValue takes precedence over the default header parsing.
|
||||
expect(tracing.propagation.getActiveBaggage()).toBe(override);
|
||||
});
|
||||
});
|
||||
|
||||
it('returns undefined baggage when no baggage header is supplied to extract', async () => {
|
||||
const tracing = tracingServiceMock.mock();
|
||||
const ctx = tracing.propagation.extract(tracing.context.active(), {
|
||||
traceparent: 'whatever',
|
||||
});
|
||||
await tracing.context.with(ctx, () => {
|
||||
expect(tracing.propagation.getActiveBaggage()).toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -21,12 +21,62 @@ import {
|
||||
import {
|
||||
TracingService,
|
||||
TracingServiceAttributeValue,
|
||||
TracingServiceBaggage,
|
||||
TracingServiceContext,
|
||||
TracingServiceContextAPI,
|
||||
TracingServicePropagationAPI,
|
||||
TracingServiceSpan,
|
||||
TracingServiceSpanStatus,
|
||||
tracingServiceRef,
|
||||
} from '@backstage/backend-plugin-api/alpha';
|
||||
import { tracingServiceFactory } from '@backstage/backend-defaults/alpha';
|
||||
|
||||
// Internal context shape used by the mock. The opaque `TracingServiceContext`
|
||||
// is just this object cast to the public type.
|
||||
interface MockContext {
|
||||
baggage?: TracingServiceBaggage;
|
||||
}
|
||||
|
||||
function toMockContext(ctx: TracingServiceContext): MockContext {
|
||||
return ctx as unknown as MockContext;
|
||||
}
|
||||
function fromMockContext(ctx: MockContext): TracingServiceContext {
|
||||
return ctx as unknown as TracingServiceContext;
|
||||
}
|
||||
|
||||
// Parses the `baggage` header per the W3C Baggage member syntax,
|
||||
// dropping value properties (`;property=value`). This mirrors what
|
||||
// `propagation.extract` does in the real tracing service, just enough
|
||||
// for tests to assert end-to-end behaviour between propagated headers
|
||||
// and `getActiveBaggage()`.
|
||||
function parseBaggageHeader(
|
||||
carrier: Record<string, string | string[] | undefined>,
|
||||
): TracingServiceBaggage | undefined {
|
||||
let raw: string | undefined;
|
||||
for (const [name, value] of Object.entries(carrier)) {
|
||||
if (name.toLowerCase() !== 'baggage') continue;
|
||||
raw = Array.isArray(value) ? value[0] : value;
|
||||
break;
|
||||
}
|
||||
if (!raw) return undefined;
|
||||
|
||||
const entries = new Map<string, { value: string }>();
|
||||
for (const segment of raw.split(',')) {
|
||||
const [pair] = segment.split(';');
|
||||
const eqIdx = pair.indexOf('=');
|
||||
if (eqIdx === -1) continue;
|
||||
const key = decodeURIComponent(pair.slice(0, eqIdx).trim());
|
||||
const value = decodeURIComponent(pair.slice(eqIdx + 1).trim());
|
||||
if (!key) continue;
|
||||
entries.set(key, { value });
|
||||
}
|
||||
if (entries.size === 0) return undefined;
|
||||
|
||||
return {
|
||||
getAllEntries: () => Array.from(entries.entries()),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A jest-mocked span captured by {@link TracingServiceMock}.
|
||||
*
|
||||
@@ -37,15 +87,61 @@ export interface MockedTracingServiceSpan extends TracingServiceSpan {
|
||||
setStatus: jest.Mock<void, [TracingServiceSpanStatus]>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Jest-mocked counterpart of the `context` member on the
|
||||
* `TracingService`.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
export interface MockedTracingServiceContextAPI
|
||||
extends TracingServiceContextAPI {
|
||||
active: jest.MockedFunction<TracingServiceContextAPI['active']>;
|
||||
with: jest.MockedFunction<TracingServiceContextAPI['with']>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Jest-mocked counterpart of the `propagation` member on the
|
||||
* `TracingService`.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
export interface MockedTracingServicePropagationAPI
|
||||
extends TracingServicePropagationAPI {
|
||||
extract: jest.MockedFunction<TracingServicePropagationAPI['extract']>;
|
||||
getBaggage: jest.MockedFunction<TracingServicePropagationAPI['getBaggage']>;
|
||||
getActiveBaggage: jest.MockedFunction<
|
||||
TracingServicePropagationAPI['getActiveBaggage']
|
||||
>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mock for the `TracingService`. Captures every span created via
|
||||
* `startActiveSpan` so tests can assert on the options passed in and the
|
||||
* methods called on the span inside the callback.
|
||||
*
|
||||
* By default, `propagation.extract` parses the `baggage` header (W3C
|
||||
* Baggage syntax) out of the supplied carrier and stashes the entries
|
||||
* on the returned context handle. `context.with` activates that handle
|
||||
* for the duration of the wrapped callback so
|
||||
* `propagation.getActiveBaggage` (and `propagation.getBaggage` on the
|
||||
* supplied handle) returns those entries. Other propagation fields
|
||||
* (e.g. `traceparent`) are ignored. Tests that need fully custom
|
||||
* baggage can still override `propagation.getActiveBaggage` via
|
||||
* `mockReturnValue` / `mockImplementation`, which takes precedence over
|
||||
* the default behaviour.
|
||||
*
|
||||
* Unlike the real `DefaultTracingService`, the mock's `startActiveSpan`
|
||||
* does **not** resolve `options.credentials` from `options.request` via
|
||||
* `httpAuth`. Tests that need principal-derived span attributes should
|
||||
* supply `options.credentials` directly on the span options, or assert
|
||||
* on the raw `options` captured by `startActiveSpan.mock.calls`.
|
||||
*
|
||||
* @alpha
|
||||
*/
|
||||
export interface TracingServiceMock extends TracingService {
|
||||
startActiveSpan: jest.MockedFunction<TracingService['startActiveSpan']>;
|
||||
context: MockedTracingServiceContextAPI;
|
||||
propagation: MockedTracingServicePropagationAPI;
|
||||
/** Spans created by `startActiveSpan` calls, in order. */
|
||||
spans: MockedTracingServiceSpan[];
|
||||
factory: ServiceFactory<TracingService>;
|
||||
@@ -66,18 +162,74 @@ export namespace tracingServiceMock {
|
||||
*/
|
||||
export const mock = (): TracingServiceMock => {
|
||||
const spans: MockedTracingServiceSpan[] = [];
|
||||
const startActiveSpan = jest.fn(async (_name, fn, _options) => {
|
||||
const span: MockedTracingServiceSpan = {
|
||||
setAttribute: jest.fn(),
|
||||
setStatus: jest.fn(),
|
||||
};
|
||||
spans.push(span);
|
||||
return await fn(span);
|
||||
}) as TracingServiceMock['startActiveSpan'];
|
||||
const startActiveSpan = jest.fn(
|
||||
async (
|
||||
_name: string,
|
||||
optionsOrFn: unknown,
|
||||
maybeFn?: (span: MockedTracingServiceSpan) => unknown,
|
||||
) => {
|
||||
const fn = (
|
||||
typeof optionsOrFn === 'function' ? optionsOrFn : maybeFn
|
||||
) as (span: MockedTracingServiceSpan) => unknown;
|
||||
const span: MockedTracingServiceSpan = {
|
||||
setAttribute: jest.fn(),
|
||||
setStatus: jest.fn(),
|
||||
};
|
||||
spans.push(span);
|
||||
return await fn(span);
|
||||
},
|
||||
) as unknown as TracingServiceMock['startActiveSpan'];
|
||||
|
||||
const service: TracingService = { startActiveSpan };
|
||||
const contextStack: MockContext[] = [{}];
|
||||
|
||||
const active = jest.fn(() =>
|
||||
fromMockContext(contextStack[contextStack.length - 1]),
|
||||
) as MockedTracingServiceContextAPI['active'];
|
||||
|
||||
const withFn = jest.fn(async (ctx, fn) => {
|
||||
contextStack.push(toMockContext(ctx));
|
||||
try {
|
||||
return await fn();
|
||||
} finally {
|
||||
contextStack.pop();
|
||||
}
|
||||
}) as MockedTracingServiceContextAPI['with'];
|
||||
|
||||
const extract = jest.fn((ctx, carrier) => {
|
||||
const baggage = parseBaggageHeader(carrier);
|
||||
// Carry forward the parsed baggage; preserve any baggage already on the
|
||||
// supplied handle if the carrier doesn't include one.
|
||||
const base = toMockContext(ctx);
|
||||
return fromMockContext({ baggage: baggage ?? base.baggage });
|
||||
}) as MockedTracingServicePropagationAPI['extract'];
|
||||
|
||||
const getBaggage = jest.fn(
|
||||
ctx => toMockContext(ctx).baggage,
|
||||
) as MockedTracingServicePropagationAPI['getBaggage'];
|
||||
|
||||
const getActiveBaggage = jest.fn(
|
||||
() => contextStack[contextStack.length - 1].baggage,
|
||||
) as MockedTracingServicePropagationAPI['getActiveBaggage'];
|
||||
|
||||
const context: MockedTracingServiceContextAPI = {
|
||||
active,
|
||||
with: withFn,
|
||||
};
|
||||
const propagation: MockedTracingServicePropagationAPI = {
|
||||
extract,
|
||||
getBaggage,
|
||||
getActiveBaggage,
|
||||
};
|
||||
|
||||
const service: TracingService = {
|
||||
startActiveSpan,
|
||||
context,
|
||||
propagation,
|
||||
};
|
||||
|
||||
return Object.assign(service as TracingServiceMock, {
|
||||
context,
|
||||
propagation,
|
||||
spans,
|
||||
factory: createServiceFactory({
|
||||
service: tracingServiceRef,
|
||||
|
||||
@@ -22,5 +22,7 @@ export {
|
||||
tracingServiceMock,
|
||||
type TracingServiceMock,
|
||||
type MockedTracingServiceSpan,
|
||||
type MockedTracingServiceContextAPI,
|
||||
type MockedTracingServicePropagationAPI,
|
||||
} from './TracingServiceMock';
|
||||
export { type ServiceMock } from './alphaCreateServiceMock';
|
||||
|
||||
Reference in New Issue
Block a user