diff --git a/src/config.ts b/src/config.ts index 129c959..649d3cb 100644 --- a/src/config.ts +++ b/src/config.ts @@ -9,7 +9,7 @@ export function setConfig(config: ResolvedTraceConfig, ctx = context.active()) { return ctx.setValue(configSymbol, config) } -export function getActiveConfig(): ResolvedTraceConfig { +export function getActiveConfig(): ResolvedTraceConfig | undefined { const config = context.active().getValue(configSymbol) as ResolvedTraceConfig - return config + return config || undefined } diff --git a/src/instrumentation/fetch.ts b/src/instrumentation/fetch.ts index 2641275..80a54ad 100644 --- a/src/instrumentation/fetch.ts +++ b/src/instrumentation/fetch.ts @@ -113,6 +113,11 @@ export function getParentContextFromHeaders(headers: Headers): Context { function getParentContextFromRequest(request: Request) { const workerConfig = getActiveConfig() + + if (workerConfig === undefined) { + return api_context.active() + } + const acceptTraceContext = typeof workerConfig.handlers.fetch.acceptTraceContext === 'function' ? workerConfig.handlers.fetch.acceptTraceContext(request) @@ -208,6 +213,9 @@ export function instrumentClientFetch( } const workerConfig = getActiveConfig() + if (!workerConfig) { + return Reflect.apply(target, thisArg, [request]) + } const config = configFn(workerConfig) const tracer = trace.getTracer('fetcher') diff --git a/src/spanprocessor.ts b/src/spanprocessor.ts index c6f40e4..55779e7 100644 --- a/src/spanprocessor.ts +++ b/src/spanprocessor.ts @@ -131,7 +131,10 @@ export class BatchTraceSpanProcessor implements SpanProcessor { } private export(localRootSpanId: string) { - const { sampling, postProcessor } = getActiveConfig() + const config = getActiveConfig() + if (!config) throw new Error('Config is undefined. This is a bug in the instrumentation logic') + + const { sampling, postProcessor } = config const exportArgs = { exporter: this.exporter, tailSampler: sampling.tailSampler, postProcessor } const newState = this.action(localRootSpanId, { actionName: 'startExport', args: exportArgs }) if (newState.stateName === 'exporting') { diff --git a/src/tracer.ts b/src/tracer.ts index 5140b19..c000aac 100644 --- a/src/tracer.ts +++ b/src/tracer.ts @@ -44,7 +44,10 @@ export class WorkerTracer implements Tracer { const spanKind = options.kind || SpanKind.INTERNAL const sanitisedAttrs = sanitizeAttributes(options.attributes) - const sampler = getActiveConfig().sampling.headSampler + const config = getActiveConfig() + if (!config) throw new Error('Config is undefined. This is a bug in the instrumentation logic') + + const sampler = config.sampling.headSampler const samplingDecision = sampler.shouldSample(context, traceId, name, spanKind, sanitisedAttrs, []) const { decision, traceState, attributes: attrs } = samplingDecision const attributes = Object.assign({}, sanitisedAttrs, attrs)