nest-xray icon indicating copy to clipboard operation
nest-xray copied to clipboard

Add support for AWS Lambda environment

Open agustinhaller opened this issue 4 years ago • 5 comments

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.

Screen Shot 2020-03-30 at 17 03 53

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?

agustinhaller avatar Mar 30 '20 20:03 agustinhaller

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.

apricote avatar Mar 31 '20 16:03 apricote

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.

agustinhaller avatar Apr 07 '20 13:04 agustinhaller

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.

apricote avatar Apr 08 '20 22:04 apricote

Any updates on lambda support?

jenssegers avatar May 31 '21 15:05 jenssegers

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

alexb-uk avatar Aug 24 '22 22:08 alexb-uk