|
| 1 | +import type { Metrics } from '@aws-lambda-powertools/metrics'; |
| 2 | +import { MetricUnit } from '@aws-lambda-powertools/metrics'; |
| 3 | +import type { Middleware, RequestContext } from '../../types/http.js'; |
| 4 | +import { HttpError } from '../errors.js'; |
| 5 | + |
| 6 | +const getHeaderMetadata = (req: Request): Record<string, string> => { |
| 7 | + const metadata: Record<string, string> = {}; |
| 8 | + |
| 9 | + const userAgent = req.headers.get('User-Agent'); |
| 10 | + if (userAgent) { |
| 11 | + metadata.userAgent = userAgent; |
| 12 | + } |
| 13 | + |
| 14 | + return metadata; |
| 15 | +}; |
| 16 | + |
| 17 | +const getIpAddress = (reqCtx: RequestContext): string | undefined => { |
| 18 | + if (reqCtx.responseType === 'ApiGatewayV1') { |
| 19 | + return reqCtx.event.requestContext.identity.sourceIp; |
| 20 | + } |
| 21 | + if (reqCtx.responseType === 'ApiGatewayV2') { |
| 22 | + return reqCtx.event.requestContext.http.sourceIp; |
| 23 | + } |
| 24 | + const xForwardedFor = reqCtx.req.headers.get('X-Forwarded-For'); |
| 25 | + if (xForwardedFor) { |
| 26 | + return xForwardedFor.split(',')[0].trim(); |
| 27 | + } |
| 28 | + return undefined; |
| 29 | +}; |
| 30 | + |
| 31 | +const getEventMetadata = (reqCtx: RequestContext): Record<string, string> => { |
| 32 | + const metadata: Record<string, string> = {}; |
| 33 | + |
| 34 | + const ipAddress = getIpAddress(reqCtx); |
| 35 | + if (ipAddress) { |
| 36 | + metadata.ipAddress = ipAddress; |
| 37 | + } |
| 38 | + |
| 39 | + if (reqCtx.responseType !== 'ALB') { |
| 40 | + metadata.apiGwRequestId = reqCtx.event.requestContext.requestId; |
| 41 | + metadata.apiGwApiId = reqCtx.event.requestContext.apiId; |
| 42 | + } |
| 43 | + if (reqCtx.responseType === 'ApiGatewayV1') { |
| 44 | + const extendedRequestId = reqCtx.event.requestContext.extendedRequestId; |
| 45 | + if (extendedRequestId) { |
| 46 | + metadata.apiGwExtendedRequestId = extendedRequestId; |
| 47 | + } |
| 48 | + } |
| 49 | + |
| 50 | + return metadata; |
| 51 | +}; |
| 52 | + |
| 53 | +/** |
| 54 | + * A middleware for emitting per-request metrics using Powertools Metrics. |
| 55 | + * |
| 56 | + * This middleware automatically: |
| 57 | + * - Adds the matched route as a metric dimension (uses `NOT_FOUND` when no route matches to prevent dimension explosion) |
| 58 | + * - Emits `latency` (Milliseconds), `fault` (Count), and `error` (Count) metrics |
| 59 | + * - Adds `httpMethod` and `path` metadata for all requests |
| 60 | + * - Adds `ipAddress` and `userAgent` metadata from request headers when available |
| 61 | + * - Adds `apiGwRequestId` and `apiGwApiId` metadata for API Gateway V1 and V2 events |
| 62 | + * - Adds `apiGwExtendedRequestId` metadata for API Gateway V1 events when available |
| 63 | + * - Publishes stored metrics after each request |
| 64 | + * |
| 65 | + * @example |
| 66 | + * ```typescript |
| 67 | + * import { Router } from '@aws-lambda-powertools/event-handler/http'; |
| 68 | + * import { metrics as metricsMiddleware } from '@aws-lambda-powertools/event-handler/http/middleware/metrics'; |
| 69 | + * import { Metrics } from '@aws-lambda-powertools/metrics'; |
| 70 | + * |
| 71 | + * const metrics = new Metrics({ namespace: 'my-app', serviceName: 'my-service' }); |
| 72 | + * const app = new Router(); |
| 73 | + * |
| 74 | + * app.use(metricsMiddleware(metrics)); |
| 75 | + * ``` |
| 76 | + * |
| 77 | + * @param metrics - The Metrics instance to use for emitting metrics |
| 78 | + */ |
| 79 | +const metrics = (metrics: Metrics): Middleware => { |
| 80 | + return async ({ reqCtx, next }) => { |
| 81 | + const start = performance.now(); |
| 82 | + let status = 500; |
| 83 | + |
| 84 | + try { |
| 85 | + await next(); |
| 86 | + status = reqCtx.res.status; |
| 87 | + } catch (error) { |
| 88 | + status = error instanceof HttpError ? error.statusCode : 500; |
| 89 | + throw error; |
| 90 | + } finally { |
| 91 | + const url = new URL(reqCtx.req.url); |
| 92 | + const metadata = { |
| 93 | + httpMethod: reqCtx.req.method, |
| 94 | + path: url.pathname, |
| 95 | + statusCode: String(status), |
| 96 | + ...getHeaderMetadata(reqCtx.req), |
| 97 | + ...getEventMetadata(reqCtx), |
| 98 | + }; |
| 99 | + for (const [key, value] of Object.entries(metadata)) { |
| 100 | + metrics.addMetadata(key, value); |
| 101 | + } |
| 102 | + metrics |
| 103 | + .addDimension('route', reqCtx.route ?? 'NOT_FOUND') |
| 104 | + .addMetric( |
| 105 | + 'latency', |
| 106 | + MetricUnit.Milliseconds, |
| 107 | + performance.now() - start |
| 108 | + ) |
| 109 | + .addMetric('fault', MetricUnit.Count, status >= 500 ? 1 : 0) |
| 110 | + .addMetric( |
| 111 | + 'error', |
| 112 | + MetricUnit.Count, |
| 113 | + status >= 400 && status < 500 ? 1 : 0 |
| 114 | + ) |
| 115 | + .publishStoredMetrics(); |
| 116 | + } |
| 117 | + }; |
| 118 | +}; |
| 119 | + |
| 120 | +export { metrics }; |
0 commit comments