-
Notifications
You must be signed in to change notification settings - Fork 232
feat(payments-api): add basic obs and monitoring #20815
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| /* This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
|
||
| import { Type } from 'class-transformer'; | ||
| import { IsNumber, IsOptional, IsString } from 'class-validator'; | ||
|
|
||
| export class SentryConfig { | ||
| @IsOptional() | ||
| @IsString() | ||
| dsn?: string; | ||
|
|
||
| @IsString() | ||
| env!: string; | ||
|
|
||
| @IsString() | ||
| serverName!: string; | ||
|
|
||
| @Type(() => Number) | ||
| @IsNumber() | ||
| sampleRate!: number; | ||
|
|
||
| @Type(() => Number) | ||
| @IsNumber() | ||
| tracesSampleRate!: number; | ||
| } | ||
|
StaberindeZA marked this conversation as resolved.
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| /* This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
|
||
| import { existsSync } from 'fs'; | ||
| import { join } from 'path'; | ||
|
|
||
| import * as dotenv from 'dotenv'; | ||
| import { initSentry } from '@fxa/shared/sentry-nest'; | ||
|
|
||
| // Sentry must initialize before `@nestjs/core` is imported so the | ||
| // SDK's async-context patches attach to every Nest handler. Nest's | ||
| // TypedConfigModule has not run yet, so pull configuration straight | ||
| // from the same `.env` files the module would load. | ||
| for (const file of ['.env.local', '.env']) { | ||
| const path = join(process.cwd(), file); | ||
| if (existsSync(path)) { | ||
| dotenv.config({ path, override: false }); | ||
| } | ||
| } | ||
|
|
||
| const parseNumber = (raw: string | undefined, fallback: number) => { | ||
| if (raw === undefined || raw === '') return fallback; | ||
| const parsed = Number(raw); | ||
| return Number.isFinite(parsed) ? parsed : fallback; | ||
| }; | ||
|
|
||
| initSentry( | ||
| { | ||
| release: process.env.APP_VERSION, | ||
| sentry: { | ||
| dsn: process.env.SENTRY_CONFIG__DSN, | ||
|
StaberindeZA marked this conversation as resolved.
|
||
| env: process.env.SENTRY_CONFIG__ENV, | ||
| serverName: process.env.SENTRY_CONFIG__SERVER_NAME, | ||
| sampleRate: parseNumber(process.env.SENTRY_CONFIG__SAMPLE_RATE, 0), | ||
| tracesSampleRate: parseNumber( | ||
| process.env.SENTRY_CONFIG__TRACES_SAMPLE_RATE, | ||
| 0 | ||
| ), | ||
| }, | ||
| }, | ||
| console | ||
| ); | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
139 changes: 139 additions & 0 deletions
139
libs/shared/metrics/statsd/src/lib/statsd-route.middleware.spec.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,139 @@ | ||
| /* This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
|
||
| import { EventEmitter } from 'events'; | ||
| import type { NextFunction, Request, Response } from 'express'; | ||
| import { StatsD } from 'hot-shots'; | ||
|
|
||
| import { StatsDRouteMiddleware } from './statsd-route.middleware'; | ||
|
|
||
| type FakeResponse = Response & { finish: () => void }; | ||
|
|
||
| const buildStatsD = (): jest.Mocked<Pick<StatsD, 'increment' | 'timing'>> => ({ | ||
| increment: jest.fn(), | ||
| timing: jest.fn(), | ||
| }); | ||
|
|
||
| const buildRequest = (overrides: Partial<Request> = {}): Request => | ||
| ({ | ||
| method: 'GET', | ||
| path: '/some/path', | ||
| ...overrides, | ||
| }) as unknown as Request; | ||
|
|
||
| const buildResponse = (statusCode = 200): FakeResponse => { | ||
| const emitter = new EventEmitter(); | ||
| const res = Object.assign(emitter, { | ||
| statusCode, | ||
| finish: () => emitter.emit('finish'), | ||
| }); | ||
| return res as unknown as FakeResponse; | ||
| }; | ||
|
|
||
| describe('StatsDRouteMiddleware', () => { | ||
| let statsd: ReturnType<typeof buildStatsD>; | ||
| let middleware: StatsDRouteMiddleware; | ||
| let next: jest.MockedFunction<NextFunction>; | ||
|
|
||
| beforeEach(() => { | ||
| statsd = buildStatsD(); | ||
| middleware = new StatsDRouteMiddleware(statsd as unknown as StatsD); | ||
| next = jest.fn(); | ||
| }); | ||
|
|
||
| it('calls next immediately and defers metric emission to the response finish event', () => { | ||
| const req = buildRequest({ route: { path: '/v1/things/:id' } } as Partial<Request>); | ||
| const res = buildResponse(200); | ||
|
|
||
| middleware.use(req, res, next); | ||
|
|
||
| expect(next).toHaveBeenCalledTimes(1); | ||
| expect(statsd.increment).not.toHaveBeenCalled(); | ||
| expect(statsd.timing).not.toHaveBeenCalled(); | ||
| }); | ||
|
|
||
| it('emits count and timing tagged with method/route/statusCode when the response finishes', () => { | ||
| const req = buildRequest({ | ||
| method: 'POST', | ||
| route: { path: '/v1/billing-and-subscriptions' }, | ||
| } as Partial<Request>); | ||
| const res = buildResponse(201); | ||
|
|
||
| middleware.use(req, res, next); | ||
| res.finish(); | ||
|
|
||
| const expectedTags = { | ||
| method: 'POST', | ||
| route: 'v1/billing-and-subscriptions', | ||
| statusCode: '201', | ||
| }; | ||
| expect(statsd.increment).toHaveBeenCalledTimes(1); | ||
| expect(statsd.increment).toHaveBeenCalledWith( | ||
| 'route.request.count', | ||
| expectedTags | ||
| ); | ||
| expect(statsd.timing).toHaveBeenCalledTimes(1); | ||
| expect(statsd.timing).toHaveBeenCalledWith( | ||
| 'route.request.duration', | ||
| expect.any(Number), | ||
| expectedTags | ||
| ); | ||
| }); | ||
|
|
||
| it('emits with statusCode 401 when a guard rejects the request', () => { | ||
| const req = buildRequest({ | ||
| route: { path: '/v1/billing-and-subscriptions' }, | ||
| } as Partial<Request>); | ||
| const res = buildResponse(401); | ||
|
|
||
| middleware.use(req, res, next); | ||
| res.finish(); | ||
|
|
||
| expect(statsd.increment).toHaveBeenCalledWith( | ||
| 'route.request.count', | ||
| expect.objectContaining({ statusCode: '401' }) | ||
| ); | ||
| }); | ||
|
|
||
| it('emits with statusCode 500 when the handler throws', () => { | ||
| const req = buildRequest({ | ||
| route: { path: '/v1/billing-and-subscriptions' }, | ||
| } as Partial<Request>); | ||
| const res = buildResponse(500); | ||
|
|
||
| middleware.use(req, res, next); | ||
| res.finish(); | ||
|
|
||
| expect(statsd.increment).toHaveBeenCalledWith( | ||
| 'route.request.count', | ||
| expect.objectContaining({ statusCode: '500' }) | ||
| ); | ||
| }); | ||
|
|
||
| it('tags route as "root" when the matched path is just "/"', () => { | ||
| const req = buildRequest({ route: { path: '/' } } as Partial<Request>); | ||
| const res = buildResponse(200); | ||
|
|
||
| middleware.use(req, res, next); | ||
| res.finish(); | ||
|
|
||
| expect(statsd.increment).toHaveBeenCalledWith( | ||
| 'route.request.count', | ||
| expect.objectContaining({ route: 'root' }) | ||
| ); | ||
| }); | ||
|
|
||
| it('tags route as "unmatched" when Express did not populate req.route', () => { | ||
| const req = buildRequest(); | ||
| const res = buildResponse(404); | ||
|
|
||
| middleware.use(req, res, next); | ||
| res.finish(); | ||
|
|
||
| expect(statsd.increment).toHaveBeenCalledWith( | ||
| 'route.request.count', | ||
| expect.objectContaining({ route: 'unmatched', statusCode: '404' }) | ||
| ); | ||
| }); | ||
| }); |
57 changes: 57 additions & 0 deletions
57
libs/shared/metrics/statsd/src/lib/statsd-route.middleware.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| /* This Source Code Form is subject to the terms of the Mozilla Public | ||
| * License, v. 2.0. If a copy of the MPL was not distributed with this | ||
| * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ | ||
|
|
||
| import { Inject, Injectable, NestMiddleware } from '@nestjs/common'; | ||
| import type { NextFunction, Request, Response } from 'express'; | ||
| import { StatsD } from 'hot-shots'; | ||
|
|
||
| import { StatsDService } from './statsd.provider'; | ||
|
|
||
| /** | ||
| * Express middleware that emits StatsD metrics for every HTTP response: | ||
| * - `route.request.count` : counter, incremented once per request | ||
| * - `route.request.duration` : timing (ms) from middleware entry to | ||
| * `res.on('finish')` (response fully flushed) | ||
| * | ||
| * Both metrics are tagged with `method`, `route`, and `statusCode`. | ||
| * `route` is `req.route.path` (the Express route pattern, e.g. | ||
| * `/subscriptions/:id`) when a handler matched, or `'unmatched'` for | ||
| * 404s and requests rejected before routing. | ||
| * | ||
| * Runs at the Express layer, before Nest's guard/interceptor pipeline, | ||
| * so it captures auth failures (401/403), pipe validation errors, | ||
| * handler exceptions, and successful responses in a single path. | ||
| */ | ||
| @Injectable() | ||
| export class StatsDRouteMiddleware implements NestMiddleware { | ||
| constructor(@Inject(StatsDService) private readonly statsd: StatsD) {} | ||
|
|
||
| use(req: Request, res: Response, next: NextFunction) { | ||
| const start = performance.now(); | ||
|
|
||
| res.on('finish', () => { | ||
| const elapsed = performance.now() - start; | ||
| const tags = { | ||
| method: req.method, | ||
| route: normalizeRoute(req.route?.path), | ||
| statusCode: String(res.statusCode), | ||
| }; | ||
| this.statsd.increment('route.request.count', tags); | ||
| this.statsd.timing('route.request.duration', elapsed, tags); | ||
| }); | ||
|
|
||
| next(); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Strips the leading `/` from an Express route pattern so downstream | ||
| * statsd receivers (Graphite/Prometheus/etc.) that sanitize `/` don't | ||
| * produce tag values like `-v1-billing-and-subscriptions`. Falls back | ||
| * to `unmatched` when no route was resolved (e.g., 404). | ||
| */ | ||
| export const normalizeRoute = (path: string | undefined): string => { | ||
| if (!path) return 'unmatched'; | ||
| return path.replace(/^\//, '') || 'root'; | ||
| }; |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.