Skip to content

Commit

Permalink
feat: added new option propagateToReply (#68)
Browse files Browse the repository at this point in the history
Closes #66
  • Loading branch information
10xLaCroixDrinker authored Apr 9, 2024
1 parent d7fa859 commit 9f19a97
Show file tree
Hide file tree
Showing 6 changed files with 55 additions and 2 deletions.
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
}))

0 comments on commit 9f19a97

Please sign in to comment.