Skip to content

Add a minimal fetch instrumentation #383

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 5 commits into from
Jul 28, 2025
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
4 changes: 1 addition & 3 deletions eslint_temporary_suppressions.js
Original file line number Diff line number Diff line change
Expand Up @@ -557,11 +557,9 @@ export default [
},
},
{
files: ['packages/otel/src/bootstrap/netlify_span_exporter.ts'],
files: ['packages/otel/src/exporters/netlify.ts'],
rules: {
'@typescript-eslint/unbound-method': 'off',
'@typescript-eslint/restrict-template-expressions': 'off',
'@typescript-eslint/no-confusing-void-expression': 'off',
},
},
{
Expand Down
2 changes: 1 addition & 1 deletion packages/otel/src/bootstrap/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ export const createTracerProvider = async (options: TracerProviderOptions) => {

const { registerInstrumentations } = await import('@opentelemetry/instrumentation')

const { NetlifySpanExporter } = await import('./netlify_span_exporter.js')
const { NetlifySpanExporter } = await import('../exporters/netlify.js')

const resource = new Resource({
'service.name': options.serviceName,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ export class NetlifySpanExporter implements SpanExporter {

/** Export spans. */
export(spans: ReadableSpan[], resultCallback: (result: ExportResult) => void): void {
this.#logger.debug(`export ${spans.length} spans`)
this.#logger.debug(`export ${spans.length.toString()} spans`)
if (this.#shutdownOnce.isCalled) {
resultCallback({
code: ExportResultCode.FAILED,
Expand All @@ -28,7 +28,7 @@ export class NetlifySpanExporter implements SpanExporter {
}

console.log(TRACE_PREFIX, NetlifySpanExporter.#decoder.decode(JsonTraceSerializer.serializeRequest(spans)))
return resultCallback({ code: ExportResultCode.SUCCESS })
resultCallback({ code: ExportResultCode.SUCCESS })
}

/**
Expand Down
112 changes: 112 additions & 0 deletions packages/otel/src/instrumentations/fetch.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import * as api from '@opentelemetry/api'
import { InstrumentationConfig, type Instrumentation } from '@opentelemetry/instrumentation'
import { _globalThis } from '@opentelemetry/core'
import { SugaredTracer } from '@opentelemetry/api/experimental'

export interface FetchInstrumentationConfig extends InstrumentationConfig {
getRequestAttributes?(request: Request | RequestInit): api.Attributes
getResponseAttributes?(response: Response): api.Attributes
skipURLs?: string[]
}

export class FetchInstrumentation implements Instrumentation {
instrumentationName = '@netlify/otel/instrumentation-fetch'
instrumentationVersion = '1.0.0'
private originalFetch: typeof fetch | null = null
private config: FetchInstrumentationConfig
private provider?: api.TracerProvider

constructor(config: FetchInstrumentationConfig = {}) {
this.config = config
}

getConfig(): FetchInstrumentationConfig {
return this.config
}

setConfig(): void {}

setMeterProvider(): void {}
setTracerProvider(provider: api.TracerProvider): void {
this.provider = provider
}
getTracerProvider(): api.TracerProvider | undefined {
return this.provider
}

private annotateFromResponse(span: api.Span, response: Response): void {
const extras = this.config.getResponseAttributes?.(response) ?? {}
// these are based on @opentelemetry/semantic-convention 1.36
span.setAttributes({
...extras,
'http.response.status_code': response.status,
...this.prepareHeaders('response', response.headers),
})
}

private annotateFromRequest(span: api.Span, request: Request): void {
const extras = this.config.getRequestAttributes?.(request) ?? {}
const url = new URL(request.url)
// these are based on @opentelemetry/semantic-convention 1.36
span.setAttributes({
...extras,
'http.request.method': request.method,
'url.full': url.href,
'url.host': url.host,
'url.scheme': url.protocol.replace(':', ''),
'server.address': url.hostname,
'server.port': url.port,
...this.prepareHeaders('request', request.headers),
})
}

private prepareHeaders(type: 'request' | 'response', headers: Headers): api.Attributes {
return Object.fromEntries(Array.from(headers.entries()).map(([key, value]) => [`${type}.header.${key}`, value]))
}

private getTracer(): SugaredTracer | undefined {
if (!this.provider) {
return undefined
}

const tracer = this.provider.getTracer(this.instrumentationName, this.instrumentationVersion)
if (tracer instanceof SugaredTracer) {
return tracer
}

return new SugaredTracer(tracer)
}

/**
* patch global fetch
*/
enable(): void {
const originalFetch = _globalThis.fetch
this.originalFetch = originalFetch
_globalThis.fetch = async (resource: RequestInfo | URL, options?: RequestInit): Promise<Response> => {
const url = typeof resource === 'string' ? resource : resource instanceof URL ? resource.href : resource.url
const tracer = this.getTracer()
if (!tracer || this.config.skipURLs?.some((skip) => url.startsWith(skip))) {
return await originalFetch(resource, options)
}

return tracer.withActiveSpan('fetch', async (span) => {
const request = new Request(resource, options)
this.annotateFromRequest(span, request)
const response = await originalFetch(resource, options)
this.annotateFromResponse(span, response)
return response
})
}
}

/**
* unpatch global fetch
*/
disable(): void {
if (this.originalFetch) {
_globalThis.fetch = this.originalFetch
this.originalFetch = null
}
}
}
2 changes: 1 addition & 1 deletion packages/otel/tsup.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export default defineConfig([
{
clean: true,
format: ['cjs', 'esm'],
entry: ['src/bootstrap/main.ts', 'src/main.ts'],
entry: ['src/bootstrap/main.ts', 'src/main.ts', 'src/exporters/netlify.ts', 'src/instrumentations/fetch.ts'],
tsconfig: 'tsconfig.json',
splitting: false,
bundle: true,
Expand Down
Loading