powertools-lambda-typescript
powertools-lambda-typescript copied to clipboard
Feature request: Add Event Handler Tracer Middleware
Use case
We should have a way of getting traces from HTTP routes in event handler so that the customer does not have to manually instrument their routes.
Solution/User Experience
We could create a middleware that behaves similarly to the Middy tracer middlware we currently have. A sample implementation could look like this:
export const tracerMiddleware = (tracer: Tracer, options?: {captureResponse?: boolean}): Middleware => {
const {captureResponse = true} = options ?? {};
return async ({ reqCtx, next }) => {
const url = new URL(reqCtx.req.url);
const subsegment = tracer.getSegment()?.addNewSubsegment(url.pathname);
subsegment && tracer.setSegment(subsegment);
tracer.annotateColdStart();
tracer.addServiceNameAnnotation();
try {
await next();
} catch(err) {
tracer.addErrorAsMetadata(err as Error);
subsegment?.close();
subsegment && tracer.setSegment(subsegment.parent);
throw err;
}
if(captureResponse && reqCtx.res.headers.get('Content-Type') === 'application/json') {
const responseBody = await reqCtx.res.clone().json() ?? {};
tracer.addResponseAsMetadata(responseBody);
}
subsegment?.close();
subsegment && tracer.setSegment(subsegment.parent);
}
}
Open questions:
- Should the middleware take multiple tracer instances like our Middy one does?
- Should the logic around capturing responses be more complex, i.e., should we disallow it when we are in streaming mode? This would require us to add data to
reqCtxto indicate when we are in HTTP streaming mode.
Alternative solutions
We could tell users to use the Middy tracer middleware.
Acknowledgment
- [x] This feature request meets Powertools for AWS Lambda (TypeScript) Tenets
- [ ] Should this be considered in other Powertools for AWS Lambda languages? i.e. Python, Java, and .NET
Future readers
Please react with 👍 and your use case to help us understand customer demand.