Skip to content

Feature request: Add Event Handler Tracer Middleware #4821

@svozza

Description

@svozza

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:

  1. Should the middleware take multiple tracer instances like our Middy one does?
  2. 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 reqCtx to indicate when we are in HTTP streaming mode.

Alternative solutions

We could tell users to use the Middy tracer middleware.

Acknowledgment

Future readers

Please react with 👍 and your use case to help us understand customer demand.

Metadata

Metadata

Assignees

No one assigned

    Labels

    confirmedThe scope is clear, ready for implementationevent-handlerThis item relates to the Event Handler Utilityfeature-requestThis item refers to a feature request for an existing or new utility

    Type

    No type

    Projects

    Status

    Backlog

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions