Skip to content
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

feat: added new option propagateToReply #68

Merged
merged 1 commit into from
Apr 9, 2024
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: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,8 @@ The plugin accepts the the following configuration properties:

- The ignored routes will still have access to `request.openTelemetry`, but `activeSpan` will be `undefined`.

- **`propagateToReply` : `boolean`** - When `true`, the current span context will be injected into the reply headers using your registered propagators. Defaults to `false`.

### Request Decorator

This plugin decorates the request with an `openTelemetry` function that returns an object with the following properties:
Expand Down Expand Up @@ -164,6 +166,8 @@ This plugin registers the following Fastify hooks:

- `onRoute`: Added only if `wrapRoutes` is enabled.

- `onSend`: Added only if `propagateToReply` is enabled.

### OpenTelemetry Compatibility

As the [OpenTelemetry API](https://github.com/open-telemetry/opentelemetry-js-api#version-compatibility) uses a
Expand Down
1 change: 1 addition & 0 deletions fastify-opentelemetry.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ declare namespace fastifyOpenTelemetry {
},
wrapRoutes?: boolean | string[],
ignoreRoutes?: string[] | ((path: string, method: string) => boolean),
propagateToReply?: boolean,
}

export const fastifyOpenTelemetry: FastifyPluginCallback<OpenTelemetryPluginOptions>
Expand Down
12 changes: 11 additions & 1 deletion index.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,8 @@ async function openTelemetryPlugin (fastify, opts = {}) {
wrapRoutes,
exposeApi = true,
formatSpanName = defaultFormatSpanName,
ignoreRoutes = []
ignoreRoutes = [],
propagateToReply = false
} = opts

const shouldIgnoreRoute = typeof ignoreRoutes === 'function'
Expand Down Expand Up @@ -146,10 +147,19 @@ async function openTelemetryPlugin (fastify, opts = {}) {
span.setAttributes(formatSpanAttributes.error(error))
}

async function onSend (request, reply, payload) {
const { inject } = request.openTelemetry()
const propagationHeaders = {}
inject(propagationHeaders)
reply.headers(propagationHeaders)
return payload
};

fastify.addHook('onRequest', onRequest)
if (wrapRoutes) fastify.addHook('onRequest', onRequestWrapRoutes)
fastify.addHook('onResponse', onResponse)
fastify.addHook('onError', onError)
if (propagateToReply) fastify.addHook('onSend', onSend)
}

module.exports = fp(openTelemetryPlugin, {
Expand Down
11 changes: 11 additions & 0 deletions test/fixtures/openTelemetryApi.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,17 @@ const {
propagation,
trace
} = require('@opentelemetry/api')
const {
BasicTracerProvider,
ConsoleSpanExporter,
SimpleSpanProcessor
} = require('@opentelemetry/sdk-trace-base')
const { W3CTraceContextPropagator } = require('@opentelemetry/core')

const provider = new BasicTracerProvider()
const exporter = new ConsoleSpanExporter()
provider.addSpanProcessor(new SimpleSpanProcessor(exporter))
provider.register({ propagator: new W3CTraceContextPropagator() })

const { name: moduleName, version: moduleVersion } = require('../../package.json')

Expand Down
26 changes: 26 additions & 0 deletions test/index.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -463,3 +463,29 @@ test('should use request.routerPath if request.routeOptions does not exist', asy
'should not contain router path when no matching routes found'
)
})

test('add propagation headers to reply when propagateToReply is true', async ({ same, teardown }) => {
const fastify = require('fastify')()

await fastify.register(openTelemetryPlugin, { wrapRoutes: true, propagateToReply: true })

async function testHandler (request, reply) {
const { activeSpan } = request.openTelemetry()
reply.headers({ one: 'ok' })
return { body: activeSpan.spanContext() }
}

fastify.get('/test', testHandler)

await fastify.ready()

teardown(() => {
resetHistory()
fastify.close()
})

const res = await fastify.inject({ ...injectArgs, url: '/test' })
const spanContext = res.json().body
same(res.statusCode, 200)
same(res.headers.traceparent, `00-${spanContext.traceId}-${spanContext.spanId}-0${spanContext.traceFlags}`)
})
3 changes: 2 additions & 1 deletion test/types/fastify-opentelemetry.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,5 +46,6 @@ expectType(<OpenTelemetryPluginOptions>({
},
ignoreRoutes: (path: string, method: string) => method === 'OPTIONS',
formatSpanName: (request: FastifyRequest) => `${request.method} constant-part`,
wrapRoutes: true
wrapRoutes: true,
propagateToReply: true
}))
Loading