Skip to content
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: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@athenna/http",
"version": "5.59.0",
"version": "5.61.0",
"description": "The Athenna Http server. Built on top of fastify.",
"license": "MIT",
"author": "João Lenon <lenon@athenna.io>",
Expand Down
5 changes: 5 additions & 0 deletions src/handlers/FastifyHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { NotFoundException } from '#src/exceptions/NotFoundException'
import type { FastifyReply, FastifyRequest, RouteHandlerMethod } from 'fastify'

const otelApi = await Module.safeImport('@opentelemetry/api')
const otelCurrentContextBagKey = Symbol.for('athenna.otel.currentContextBag')

export class FastifyHandler {
/**
Expand Down Expand Up @@ -132,6 +133,7 @@ export class FastifyHandler {
}

let otelContext = otelApi.context.active()
const bag = new Map<string | symbol, unknown>()

for (const binding of Config.get('http.otel.contextBindings', [])) {
const value = binding.resolve(ctx)
Expand All @@ -140,9 +142,12 @@ export class FastifyHandler {
continue
}

bag.set(binding.key, value)
otelContext = otelContext.setValue(binding.key, value)
}

req.data.otelCurrentContextBag = bag
otelContext = otelContext.setValue(otelCurrentContextBagKey as any, bag)
req.otelContext = otelContext

return otelContext as OtelContext
Expand Down
81 changes: 81 additions & 0 deletions tests/unit/server/ServerTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ import { context, createContextKey } from '@opentelemetry/api'
import { Test, AfterEach, BeforeEach, type Context, Cleanup } from '@athenna/test'
import { AsyncLocalStorageContextManager } from '@opentelemetry/context-async-hooks'

const otelCurrentContextBagKey = Symbol.for('athenna.otel.currentContextBag')

export default class ServerTest {
@BeforeEach()
public async beforeEach() {
Expand Down Expand Up @@ -266,6 +268,44 @@ export default class ServerTest {
})
}

@Test()
@Cleanup(() => Config.set('http.otel.contextEnabled', false))
@Cleanup(() => Config.set('http.otel.contextBindings', []))
public async shouldCreateAndReuseTheSameRequestContextBagAcrossTheLifecycle({ assert }: Context) {
const exampleIdKey = 'exampleId'
let requestBag: Map<string | symbol, unknown> = null
let terminateBag: Map<string | symbol, unknown> = null

Config.set('http.otel.contextEnabled', true)
Config.set('http.otel.contextBindings', [{ key: exampleIdKey, resolve: () => 'example-id-from-binding' }])

Server.terminate(() => {
terminateBag = context.active().getValue(otelCurrentContextBagKey as any) as Map<
string | symbol,
unknown
>
}).get({
url: '/test',
handler: async ctx => {
requestBag = context.active().getValue(otelCurrentContextBagKey as any) as Map<
string | symbol,
unknown
>
requestBag.set(exampleIdKey, 'example-id-from-handler')

await ctx.response.send({
exampleId: requestBag.get(exampleIdKey)
})
}
})

const response = await Server.request().get('/test')

assert.deepEqual(response.json(), { exampleId: 'example-id-from-handler' })
assert.strictEqual(requestBag, terminateBag)
assert.equal(terminateBag.get(exampleIdKey), 'example-id-from-handler')
}

@Test()
@Cleanup(() => Config.set('http.otel.contextEnabled', false))
@Cleanup(() => Config.set('http.otel.contextBindings', []))
Expand Down Expand Up @@ -293,4 +333,45 @@ export default class ServerTest {
assert.equal(response.statusCode, 500)
assert.deepEqual(response.json(), { route: '/boom' })
}

@Test()
@Cleanup(() => Config.set('http.otel.contextEnabled', false))
@Cleanup(() => Config.set('http.otel.contextBindings', []))
public async shouldExposeTheSameRequestContextBagInsideErrorHandlers({ assert }: Context) {
let requestBag: Map<string | symbol, unknown> = null
let errorBag: Map<string | symbol, unknown> = null

Config.set('http.otel.contextEnabled', true)
Config.set('http.otel.contextBindings', [{ key: 'exampleId', resolve: () => 'example-id-from-binding' }])

Server.setErrorHandler(async ctx => {
errorBag = context.active().getValue(otelCurrentContextBagKey as any) as Map<
string | symbol,
unknown
>

await ctx.response.status(500).send({
exampleId: errorBag.get('exampleId')
})
})

Server.get({
url: '/boom',
handler: async () => {
requestBag = context.active().getValue(otelCurrentContextBagKey as any) as Map<
string | symbol,
unknown
>
requestBag.set('exampleId', 'example-id-from-handler')

throw new Error('boom')
}
})

const response = await Server.request().get('/boom')

assert.equal(response.statusCode, 500)
assert.deepEqual(response.json(), { exampleId: 'example-id-from-handler' })
assert.strictEqual(requestBag, errorBag)
}
}
Loading