nest-xray
nest-xray copied to clipboard
Add support for AWS Lambda environment
Hi, I enabled X-Ray in my AWS Lambda function (which creates automatic traces in X-Ray) Now I'm creating a sub segment inside a service in my NestJs API running on AWS Lambda. I can see the annotations and the custom sub segment trace, but it's not attached to the trace that AWS Lambda creates automatically.
I'm initializing the TracingModule like this:
@Module({
imports: [
TracingModule.forRoot({ serviceName: 'NestJS-API' }),
...
],
controllers: [AppController]
})
export class AppModule {}
And using the TracingService like this:
async findAll(): Promise<BlogPost[]> {
const subSegment = this.tracingService.createSubSegment('external-doThing');
let response: any;
try {
subSegment.addAnnotation('customKey', 'custom Value');
response = await this.blogPostsRepository.find({ relations: ["author"] });
} catch (err) {
subSegment.close(err);
throw err;
}
subSegment.close();
return response;
}
Can you point me in the right direction?
This module currently only supports reading the Trace Segment from incoming request headers.
Looking at the code for aws-xray-sdk-node
, it seems that in a Lambda Environment, the X-Ray Trace ID is contained in the environment instead (reference).
We might be able to get this to work by creating a custom Segment with the trace id from the environment, similar to what the SDK is doing here and persisting that with the TracingService
(using TracingService#setRootSegment
). Then you can use the TracingService
as usual.
I would be glad to accept a PR for this. Otherwise I might get to it in the next weeks.
Thanks for the hints. Will try to convince team to move the priority of this task up and allocate some time to come up with a PR.
I thought about the way we could implement these different strategies to read the incoming trace and created #82 to refactor the code base to allow this.
Any updates on lambda support?
I've spent quite some time trying to get this to work but I seem to have hit a wall on
Tracing was used in a code path that is not wrapped in AsyncContext#run. Please make sure that the appropriate middleware/interceptor for your environment is executed.
I'm trying to see how to create an interceptor to initialise the AsyncContext
but am not fully understanding what's needed.
If anyone has some hints or examples that would be great.
Thanks