diff --git a/CLAUDE.md b/CLAUDE.md index 0572f31..1af7a68 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,11 +39,12 @@ Nx monorepo, pnpm, NestJS. Every app is built with webpack into `dist/apps/ - `metering-subscriber`: Pub/Sub consumer on port 3038 that dedupes events in Redis and writes them to ClickHouse. Only serves heartbeat endpoints over HTTP. - `metering-sweep`: long-running process on port 3039 that runs the threshold sweep (dispatching webhooks) on a cron schedule, on one instance at a time via a Redis lock. Only serves heartbeat endpoints over HTTP. - `metering-metrics`: long-running process on port 3040 that sends usage gauges for each swept meter to StatsD on a cron schedule, on one instance at a time via a Redis lock. Only serves heartbeat endpoints over HTTP. + - Every app also serves Prometheus `GET /metrics` on its own in-cluster port (`PROMETHEUS_CONFIG__PORT`, default 9464), outside the Nest HTTP app. Never expose it through an ingress. - **Libraries (`libs/*`):** - `libs/metering`: all metering domain logic, controllers, ClickHouse client, and ClickHouse migrations. - `libs/shared/cms`: Strapi GraphQL client with memory and Firestore caching, and the meter configuration query. - - `libs/shared/*`: StatsD, Firestore, type-cacheable adapters, the Redis lock store, base errors, Sentry setup, and NestJS API helpers. + - `libs/shared/*`: StatsD, Prometheus, Firestore, type-cacheable adapters, the Redis lock store, base errors, Sentry setup, and NestJS API helpers. - **Conventions:** - **Imports:** use `@entitlements/` aliases from `tsconfig.base.json` (e.g., `@entitlements/shared/error`); avoid deep relative imports across library boundaries. diff --git a/README.md b/README.md index 4211a9f..16ab1f8 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,8 @@ This is an [Nx](https://nx.dev) monorepo using pnpm and NestJS. | `metering-sweep` | 3039 | Rebuilds Redis usage counters if needed and dispatches threshold webhooks, every minute. | | `metering-metrics` | 3040 | Sends usage gauges for every swept meter to StatsD, every 5 minutes. | +Each app also serves Prometheus metrics at `GET /metrics` on a separate port, 9464 by default (`PROMETHEUS_CONFIG__PORT`). Keep that port in-cluster. Locally, compose maps it to 9464–9467 for the apps in table order. + Shared code lives in `libs/`. The domain logic is in `libs/metering`. ## Prerequisites diff --git a/apps/api/src/app/app.module.ts b/apps/api/src/app/app.module.ts index fd4fbc7..9299c4e 100644 --- a/apps/api/src/app/app.module.ts +++ b/apps/api/src/app/app.module.ts @@ -12,6 +12,7 @@ import { AppService } from './app.service'; import { RootConfigModule } from '../config/config.module'; import { ClickHouseClient, + ClickHouseMetrics, ClickHouseRateLimitersProvider, MeteringAuthGuard, MeteringEventsManager, @@ -27,7 +28,9 @@ import { UsageCountersManager, UsageGrantsController, UsageGrantsManager, + UsageGrantsMetrics, UsageGrantsService, + UsageMetrics, UsageService, } from '@entitlements/metering'; import { @@ -35,6 +38,11 @@ import { StrapiClient, } from '@entitlements/shared/cms'; import { FirestoreProvider } from '@entitlements/shared/db/firestore'; +import { + PrometheusRegistryProvider, + PrometheusRouteMiddleware, + PrometheusServer, +} from '@entitlements/shared/metrics/prometheus'; import { StatsDProvider, StatsDRouteMiddleware, @@ -64,6 +72,11 @@ import { MeteringRedisClientProvider, MeteringSweepManager, MeteringSweepRepository, + ClickHouseMetrics, + UsageGrantsMetrics, + UsageMetrics, + PrometheusRegistryProvider, + PrometheusServer, StatsDProvider, StrapiClient, UsageCountersManager, @@ -75,7 +88,7 @@ import { export class AppModule implements NestModule { configure(consumer: MiddlewareConsumer) { consumer - .apply(StatsDRouteMiddleware) + .apply(StatsDRouteMiddleware, PrometheusRouteMiddleware) .exclude( { path: '__heartbeat__', method: RequestMethod.GET }, { path: '__lbheartbeat__', method: RequestMethod.GET }, diff --git a/apps/api/src/config/index.ts b/apps/api/src/config/index.ts index fe8285b..c578be7 100644 --- a/apps/api/src/config/index.ts +++ b/apps/api/src/config/index.ts @@ -11,6 +11,7 @@ import type { LogLevel } from '@nestjs/common'; import { MeteringConfig } from '@entitlements/metering'; import { StrapiClientConfig } from '@entitlements/shared/cms'; import { FirestoreConfig } from '@entitlements/shared/db/firestore'; +import { PrometheusConfig } from '@entitlements/shared/metrics/prometheus'; import { StatsDConfig } from '@entitlements/shared/metrics/statsd'; import { SentryConfig } from './sentry.config'; @@ -35,6 +36,10 @@ export class RootConfig { @IsDefined() public readonly statsDConfig!: Partial; + @Type(() => PrometheusConfig) + @ValidateNested() + public readonly prometheusConfig: PrometheusConfig = new PrometheusConfig(); + @Type(() => SentryConfig) @ValidateNested() @IsDefined() diff --git a/apps/metering-metrics/src/app/app.module.ts b/apps/metering-metrics/src/app/app.module.ts index 076a046..93caef6 100644 --- a/apps/metering-metrics/src/app/app.module.ts +++ b/apps/metering-metrics/src/app/app.module.ts @@ -10,6 +10,7 @@ import { SentryGlobalFilter, SentryModule } from '@sentry/nestjs/setup'; import { ClickHouseClient, + ClickHouseMetrics, ClickHouseRateLimitersProvider, MeteringLockRedisClientProvider, MeteringMetricsManager, @@ -19,6 +20,8 @@ import { MeteringSchedulerService, MeteringSweepManager, MeteringSweepRepository, + MetricsReportMetrics, + SchedulerMetrics, } from '@entitlements/metering'; import { MeteringConfigurationManager, @@ -26,6 +29,10 @@ import { } from '@entitlements/shared/cms'; import { FirestoreProvider } from '@entitlements/shared/db/firestore'; import { RedisLockStore } from '@entitlements/shared/locks'; +import { + PrometheusRegistryProvider, + PrometheusServer, +} from '@entitlements/shared/metrics/prometheus'; import { StatsDProvider, StatsDService, @@ -64,6 +71,11 @@ import { AppService } from './app.service'; MeteringSchedulerService, MeteringSweepManager, MeteringSweepRepository, + ClickHouseMetrics, + MetricsReportMetrics, + SchedulerMetrics, + PrometheusRegistryProvider, + PrometheusServer, StatsDProvider, StrapiClient, ], diff --git a/apps/metering-metrics/src/config/index.ts b/apps/metering-metrics/src/config/index.ts index 53f2a06..1cc8d4b 100644 --- a/apps/metering-metrics/src/config/index.ts +++ b/apps/metering-metrics/src/config/index.ts @@ -8,6 +8,7 @@ import { } from '@entitlements/metering'; import { StrapiClientConfig } from '@entitlements/shared/cms'; import { FirestoreConfig } from '@entitlements/shared/db/firestore'; +import { PrometheusConfig } from '@entitlements/shared/metrics/prometheus'; import { StatsDConfig } from '@entitlements/shared/metrics/statsd'; import { SentryConfig } from './sentry.config'; @@ -32,6 +33,10 @@ export class RootConfig { @IsDefined() public readonly statsDConfig!: Partial; + @Type(() => PrometheusConfig) + @ValidateNested() + public readonly prometheusConfig: PrometheusConfig = new PrometheusConfig(); + @Type(() => SentryConfig) @ValidateNested() @IsDefined() diff --git a/apps/metering-subscriber/src/app/app.module.ts b/apps/metering-subscriber/src/app/app.module.ts index 4c76861..5ae352a 100644 --- a/apps/metering-subscriber/src/app/app.module.ts +++ b/apps/metering-subscriber/src/app/app.module.ts @@ -6,7 +6,9 @@ import { AppService } from './app.service'; import { RootConfigModule } from '../config/config.module'; import { ClickHouseClient, + ClickHouseMetrics, ClickHouseRateLimitersProvider, + ConsumerMetrics, MeteringConsumerService, MeteringEventsManager, MeteringEventsRepository, @@ -19,6 +21,10 @@ import { StrapiClient, } from '@entitlements/shared/cms'; import { FirestoreProvider } from '@entitlements/shared/db/firestore'; +import { + PrometheusRegistryProvider, + PrometheusServer, +} from '@entitlements/shared/metrics/prometheus'; import { StatsDProvider } from '@entitlements/shared/metrics/statsd'; @Module({ @@ -40,6 +46,10 @@ import { StatsDProvider } from '@entitlements/shared/metrics/statsd'; MeteringEventsRepository, MeteringPubSubClientProvider, MeteringRedisClientProvider, + ClickHouseMetrics, + ConsumerMetrics, + PrometheusRegistryProvider, + PrometheusServer, StatsDProvider, StrapiClient, UsageCountersManager, diff --git a/apps/metering-subscriber/src/config/index.ts b/apps/metering-subscriber/src/config/index.ts index 4ed43d1..b3e634f 100644 --- a/apps/metering-subscriber/src/config/index.ts +++ b/apps/metering-subscriber/src/config/index.ts @@ -5,6 +5,7 @@ import type { LogLevel } from '@nestjs/common'; import { MeteringConfig } from '@entitlements/metering'; import { StrapiClientConfig } from '@entitlements/shared/cms'; import { FirestoreConfig } from '@entitlements/shared/db/firestore'; +import { PrometheusConfig } from '@entitlements/shared/metrics/prometheus'; import { StatsDConfig } from '@entitlements/shared/metrics/statsd'; import { SentryConfig } from './sentry.config'; @@ -29,6 +30,10 @@ export class RootConfig { @IsDefined() public readonly statsDConfig!: Partial; + @Type(() => PrometheusConfig) + @ValidateNested() + public readonly prometheusConfig: PrometheusConfig = new PrometheusConfig(); + @Type(() => SentryConfig) @ValidateNested() @IsDefined() diff --git a/apps/metering-sweep/src/app/app.module.ts b/apps/metering-sweep/src/app/app.module.ts index e1d51f2..cd964b2 100644 --- a/apps/metering-sweep/src/app/app.module.ts +++ b/apps/metering-sweep/src/app/app.module.ts @@ -10,6 +10,7 @@ import { SentryGlobalFilter, SentryModule } from '@sentry/nestjs/setup'; import { ClickHouseClient, + ClickHouseMetrics, ClickHouseRateLimitersProvider, MeteringFirestoreProvider, MeteringLockRedisClientProvider, @@ -20,11 +21,16 @@ import { MeteringSweepRepository, MeteringSweepService, MeteringWebhookManager, + RefillMetrics, + SchedulerMetrics, + SweepMetrics, UsageCountersManager, UsageGrantsManager, + UsageGrantsMetrics, UsageRefillManager, UsageRefillRepository, UsageRefillService, + WebhookMetrics, } from '@entitlements/metering'; import { MeteringConfigurationManager, @@ -32,6 +38,10 @@ import { } from '@entitlements/shared/cms'; import { FirestoreProvider } from '@entitlements/shared/db/firestore'; import { RedisLockStore } from '@entitlements/shared/locks'; +import { + PrometheusRegistryProvider, + PrometheusServer, +} from '@entitlements/shared/metrics/prometheus'; import { StatsDProvider, StatsDService, @@ -71,6 +81,14 @@ import { AppService } from './app.service'; MeteringSweepRepository, MeteringSweepService, MeteringWebhookManager, + ClickHouseMetrics, + RefillMetrics, + SchedulerMetrics, + SweepMetrics, + UsageGrantsMetrics, + WebhookMetrics, + PrometheusRegistryProvider, + PrometheusServer, StatsDProvider, StrapiClient, UsageCountersManager, diff --git a/apps/metering-sweep/src/config/index.ts b/apps/metering-sweep/src/config/index.ts index f375238..8733a55 100644 --- a/apps/metering-sweep/src/config/index.ts +++ b/apps/metering-sweep/src/config/index.ts @@ -8,6 +8,7 @@ import { } from '@entitlements/metering'; import { StrapiClientConfig } from '@entitlements/shared/cms'; import { FirestoreConfig } from '@entitlements/shared/db/firestore'; +import { PrometheusConfig } from '@entitlements/shared/metrics/prometheus'; import { StatsDConfig } from '@entitlements/shared/metrics/statsd'; import { SentryConfig } from './sentry.config'; @@ -32,6 +33,10 @@ export class RootConfig { @IsDefined() public readonly statsDConfig!: Partial; + @Type(() => PrometheusConfig) + @ValidateNested() + public readonly prometheusConfig: PrometheusConfig = new PrometheusConfig(); + @Type(() => SentryConfig) @ValidateNested() @IsDefined() diff --git a/dev.env b/dev.env index 529a386..5bcdb5a 100644 --- a/dev.env +++ b/dev.env @@ -24,6 +24,9 @@ STATS_D_CONFIG__HOST= STATS_D_CONFIG__PORT= STATS_D_CONFIG__PREFIX= +# Prometheus Config +PROMETHEUS_CONFIG__PORT=9464 + # Metering Config METERING_CONFIG__CLIENTS={"local-rp":"local-dev-secret"} METERING_CONFIG__USAGE_GRANTS__FIRESTORE_COLLECTION_NAME=metering-usage-grants diff --git a/docker-compose-development.yaml b/docker-compose-development.yaml index dd8b55a..4af3068 100644 --- a/docker-compose-development.yaml +++ b/docker-compose-development.yaml @@ -27,6 +27,7 @@ services: PORT: 3037 ports: - '3037:3037' + - '9464:9464' healthcheck: test: [ @@ -54,6 +55,7 @@ services: PORT: 3038 ports: - '3038:3038' + - '9465:9464' depends_on: api: condition: service_healthy @@ -67,6 +69,7 @@ services: PORT: 3039 ports: - '3039:3039' + - '9466:9464' depends_on: clickhouse-migrate: condition: service_completed_successfully @@ -82,6 +85,7 @@ services: PORT: 3040 ports: - '3040:3040' + - '9467:9464' depends_on: clickhouse-migrate: condition: service_completed_successfully diff --git a/libs/metering/src/index.ts b/libs/metering/src/index.ts index 6205f32..37ac0b9 100644 --- a/libs/metering/src/index.ts +++ b/libs/metering/src/index.ts @@ -9,6 +9,7 @@ export * from './lib/metering.schema'; export * from './lib/metering.types'; export * from './lib/clickhouse.client'; +export * from './lib/clickhouse.metrics'; export * from './lib/clickhouse.config'; export * from './lib/metering-firestore.config'; export * from './lib/metering-firestore.provider'; @@ -23,6 +24,7 @@ export * from './lib/metering-auth.guard'; export * from './lib/metering-exception.filter'; export * from './lib/metering-consumer.service'; +export * from './lib/metering-consumer.metrics'; export * from './lib/metering-redis.provider'; export * from './lib/clickhouse-rate-limiter.provider'; export * from './lib/metering-events.manager'; @@ -31,22 +33,29 @@ export * from './lib/metering-lock.provider'; export * from './lib/metering-metrics.manager'; export * from './lib/metering-metrics.repository'; export * from './lib/metering-metrics.service'; +export * from './lib/metering-metrics.metrics'; export * from './lib/metering-publisher.manager'; export * from './lib/metering-metrics-scheduler.service'; export * from './lib/metering-scheduler.service'; +export * from './lib/metering-scheduler.metrics'; export * from './lib/metering-sweep-scheduler.service'; export * from './lib/metering-sweep.manager'; export * from './lib/metering-sweep.repository'; export * from './lib/metering-sweep.service'; +export * from './lib/metering-sweep.metrics'; export * from './lib/metering-webhook.manager'; +export * from './lib/metering-webhook.metrics'; export * from './lib/usage.controller'; export * from './lib/usage.service'; +export * from './lib/usage.metrics'; export * from './lib/usage-counters.manager'; export * from './lib/usage-refill.manager'; export * from './lib/usage-refill.repository'; export * from './lib/usage-refill.service'; +export * from './lib/usage-refill.metrics'; export * from './lib/usage-grants.controller'; export * from './lib/usage-grants.manager'; +export * from './lib/usage-grants.metrics'; export * from './lib/usage-grants.schema'; export * from './lib/usage-grants.service'; diff --git a/libs/metering/src/lib/clickhouse-rate-limiter.provider.in.spec.ts b/libs/metering/src/lib/clickhouse-rate-limiter.provider.in.spec.ts index 6d9fc69..3b08f00 100644 --- a/libs/metering/src/lib/clickhouse-rate-limiter.provider.in.spec.ts +++ b/libs/metering/src/lib/clickhouse-rate-limiter.provider.in.spec.ts @@ -6,6 +6,7 @@ import 'reflect-metadata'; import Redis from 'ioredis'; import { RateLimiterRedis } from 'rate-limiter-flexible'; +import { Registry } from '@prometheus-io/client'; import { z } from 'zod'; import { StatsD } from '@entitlements/shared/metrics/statsd'; @@ -14,6 +15,7 @@ import { connectRateLimiterStore } from './clickhouse-rate-limiter.provider'; import { ClickHouseClient } from './clickhouse.client'; import { MockMeteringRedisConfig } from './metering-redis.config'; import { INTEGRATION_CLICKHOUSE_CONFIG } from '../testing'; +import { ClickHouseMetrics } from './clickhouse.metrics'; import { ClickHouseRateLimitError } from './metering.error'; const REDIS_HOST = process.env['REDIS_TEST_HOST'] ?? 'localhost'; @@ -45,6 +47,7 @@ describe('ClickHouse rate limiters against a real Redis', () => { return new ClickHouseClient( INTEGRATION_CLICKHOUSE_CONFIG, new StatsD({ mock: true }), + new ClickHouseMetrics(new Registry()), { read: new RateLimiterRedis({ storeClient, diff --git a/libs/metering/src/lib/clickhouse.client.spec.ts b/libs/metering/src/lib/clickhouse.client.spec.ts index 84243e8..bddfd82 100644 --- a/libs/metering/src/lib/clickhouse.client.spec.ts +++ b/libs/metering/src/lib/clickhouse.client.spec.ts @@ -4,6 +4,7 @@ import 'reflect-metadata'; +import type { Registry } from '@prometheus-io/client'; import { RateLimiterMemory } from 'rate-limiter-flexible'; import { z } from 'zod'; @@ -11,12 +12,14 @@ import { StatsD } from '@entitlements/shared/metrics/statsd'; import { ClickHouseClient } from './clickhouse.client'; import { ClickHouseConfig } from './clickhouse.config'; +import { ClickHouseMetrics } from './clickhouse.metrics'; import { ClickHouseError, ClickHouseRateLimitError, ClickHouseTableNameError, } from './metering.error'; import type { ClickHouseRateLimiters } from './metering.types'; +import { incrementedMetricValues, testMetrics } from '../testing'; const rowSchema = z.object({ subject: z.string(), usage: z.number() }); @@ -26,6 +29,8 @@ describe('ClickHouseClient', () => { let statsd: StatsD; let increment: jest.SpyInstance; let rateLimiters: ClickHouseRateLimiters; + let registry: Registry; + let metrics: ClickHouseMetrics; const config: ClickHouseConfig = { url: 'https://clickhouse.example.com:8443', @@ -74,7 +79,8 @@ describe('ClickHouseClient', () => { duration: 60, }), }; - client = new ClickHouseClient(config, statsd, rateLimiters); + ({ registry, metrics } = testMetrics(ClickHouseMetrics)); + client = new ClickHouseClient(config, statsd, metrics, rateLimiters); }); afterEach(() => { @@ -162,6 +168,7 @@ describe('ClickHouseClient', () => { password: undefined, }, statsd, + metrics, rateLimiters ); @@ -314,6 +321,19 @@ describe('ClickHouseClient', () => { ); }); + it('records a rejection in Prometheus with its operation and budget', async () => { + await spendReadBudget(); + + await client.query({ sql: 'SELECT 1', rowSchema }).catch(() => undefined); + + expect( + await incrementedMetricValues( + registry, + 'metering_clickhouse_limit_rejected_total' + ) + ).toEqual([{ value: 1, labels: { operation: 'query', budget: 'read' } }]); + }); + it('draws usage fallback reads from their own budget, independent of reads', async () => { await spendReadBudget(); @@ -410,6 +430,21 @@ describe('ClickHouseClient', () => { ); }); + it('records a limiter store failure in Prometheus with its operation and budget', async () => { + jest + .spyOn(rateLimiters.read, 'consume') + .mockRejectedValue(new Error('redis unavailable')); + + await client.query({ sql: 'SELECT 1', rowSchema }).catch(() => undefined); + + expect( + await incrementedMetricValues( + registry, + 'metering_clickhouse_limiter_errors_total' + ) + ).toEqual([{ value: 1, labels: { operation: 'query', budget: 'read' } }]); + }); + it('draws streams from the read budget', async () => { await spendReadBudget(); diff --git a/libs/metering/src/lib/clickhouse.client.ts b/libs/metering/src/lib/clickhouse.client.ts index 5082d93..eb100ef 100644 --- a/libs/metering/src/lib/clickhouse.client.ts +++ b/libs/metering/src/lib/clickhouse.client.ts @@ -11,6 +11,7 @@ import { type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { ClickHouseMetrics } from './clickhouse.metrics'; import { ClickHouseRateLimitersToken } from './clickhouse-rate-limiter.provider'; import { ClickHouseConfig } from './clickhouse.config'; import { @@ -55,6 +56,7 @@ export class ClickHouseClient { constructor( clickHouseConfig: ClickHouseConfig, @Inject(StatsDService) private readonly statsd: StatsD, + private readonly metrics: ClickHouseMetrics, @Inject(ClickHouseRateLimitersToken) private readonly rateLimiters: ClickHouseRateLimiters ) { @@ -190,12 +192,14 @@ export class ClickHouseClient { operation, budget, }); + this.metrics.limitRejected.inc({ operation, budget }); throw new ClickHouseRateLimitError(operation); } this.statsd.increment('metering.clickhouse.limiter_error', { operation, budget, }); + this.metrics.limiterErrors.inc({ operation, budget }); if (budget !== 'write') { throw new ClickHouseRateLimitError(operation); } diff --git a/libs/metering/src/lib/clickhouse.metrics.spec.ts b/libs/metering/src/lib/clickhouse.metrics.spec.ts new file mode 100644 index 0000000..05dd109 --- /dev/null +++ b/libs/metering/src/lib/clickhouse.metrics.spec.ts @@ -0,0 +1,34 @@ +/* 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 { Registry } from '@prometheus-io/client'; + +import { ClickHouseMetrics } from './clickhouse.metrics'; +import { metricValues, zeroMetricValues } from '../testing'; + +describe('ClickHouseMetrics', () => { + let registry: Registry; + + beforeEach(() => { + registry = new Registry(); + }); + + it.each([ + 'metering_clickhouse_limit_rejected_total', + 'metering_clickhouse_limiter_errors_total', + ])('starts %s at zero for each operation and its budgets', async (name) => { + new ClickHouseMetrics(registry); + + expect(await metricValues(registry, name)).toEqual( + zeroMetricValues([ + { operation: 'query', budget: 'read' }, + { operation: 'query', budget: 'usageFallback' }, + { operation: 'stream', budget: 'read' }, + { operation: 'stream', budget: 'usageFallback' }, + { operation: 'insert', budget: 'write' }, + { operation: 'command', budget: 'write' }, + ]) + ); + }); +}); diff --git a/libs/metering/src/lib/clickhouse.metrics.ts b/libs/metering/src/lib/clickhouse.metrics.ts new file mode 100644 index 0000000..f9d0242 --- /dev/null +++ b/libs/metering/src/lib/clickhouse.metrics.ts @@ -0,0 +1,45 @@ +/* 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 } from '@nestjs/common'; +import type { Registry } from '@prometheus-io/client'; + +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; + +import type { ClickHouseReadBudget } from './clickhouse.client'; +import { allOf, counter, initialize } from './utils/metrics'; + +@Injectable() +export class ClickHouseMetrics { + readonly limitRejected; + readonly limiterErrors; + + constructor(@Inject(PrometheusRegistry) registry: Registry) { + this.limitRejected = counter( + registry, + 'metering_clickhouse_limit_rejected_total', + 'ClickHouse operations rejected by the rate limiter', + ['operation', 'budget'] + ); + this.limiterErrors = counter( + registry, + 'metering_clickhouse_limiter_errors_total', + 'ClickHouse rate limiter failures', + ['operation', 'budget'] + ); + const readBudgets = allOf({ + read: true, + usageFallback: true, + }); + const operations = [ + ...['query', 'stream'].flatMap((operation) => + readBudgets.map((budget) => ({ operation, budget })) + ), + { operation: 'insert', budget: 'write' }, + { operation: 'command', budget: 'write' }, + ]; + initialize(this.limitRejected, operations); + initialize(this.limiterErrors, operations); + } +} diff --git a/libs/metering/src/lib/metering-consumer.metrics.spec.ts b/libs/metering/src/lib/metering-consumer.metrics.spec.ts new file mode 100644 index 0000000..e43acbd --- /dev/null +++ b/libs/metering/src/lib/metering-consumer.metrics.spec.ts @@ -0,0 +1,36 @@ +/* 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 { Registry } from '@prometheus-io/client'; + +import { ConsumerMetrics } from './metering-consumer.metrics'; +import { metricValues, zeroMetricValues } from '../testing'; + +describe('ConsumerMetrics', () => { + let registry: Registry; + + beforeEach(() => { + registry = new Registry(); + }); + + it('starts each consumer error stage at zero', async () => { + new ConsumerMetrics(registry); + + expect( + await metricValues(registry, 'metering_consumer_errors_total') + ).toEqual( + zeroMetricValues( + [ + 'confirm', + 'dedupe', + 'flush', + 'insert', + 'invalid', + 'meter', + 'subscription', + ].map((stage) => ({ stage })) + ) + ); + }); +}); diff --git a/libs/metering/src/lib/metering-consumer.metrics.ts b/libs/metering/src/lib/metering-consumer.metrics.ts new file mode 100644 index 0000000..4dc1a56 --- /dev/null +++ b/libs/metering/src/lib/metering-consumer.metrics.ts @@ -0,0 +1,83 @@ +/* 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 } from '@nestjs/common'; +import type { Registry } from '@prometheus-io/client'; + +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; + +import { allOf, counter, initialize } from './utils/metrics'; + +export type ConsumerErrorStage = + | 'confirm' + | 'dedupe' + | 'flush' + | 'insert' + | 'invalid' + | 'meter' + | 'subscription'; + +@Injectable() +export class ConsumerMetrics { + readonly received; + readonly paused; + readonly pending; + readonly duplicates; + readonly inserted; + readonly insertedAmount; + readonly errors; + + constructor(@Inject(PrometheusRegistry) registry: Registry) { + this.received = counter( + registry, + 'metering_consumer_received_total', + 'Pub/Sub messages received' + ); + this.paused = counter( + registry, + 'metering_consumer_paused_total', + 'Messages nacked while ingest is paused' + ); + this.pending = counter( + registry, + 'metering_consumer_pending_total', + 'Messages nacked while their dedupe key is pending elsewhere' + ); + this.duplicates = counter( + registry, + 'metering_consumer_duplicate_total', + 'Duplicate messages acked without inserting' + ); + this.inserted = counter( + registry, + 'metering_consumer_inserted_total', + 'Events inserted into ClickHouse', + ['client_id', 'slug'] + ); + this.insertedAmount = counter( + registry, + 'metering_consumer_inserted_amount_total', + 'Usage amount inserted into ClickHouse', + ['client_id', 'slug'] + ); + this.errors = counter<'stage'>( + registry, + 'metering_consumer_errors_total', + 'Consumer failures by stage', + ['stage'] + ); + initialize( + this.errors, + allOf({ + confirm: true, + dedupe: true, + flush: true, + insert: true, + invalid: true, + meter: true, + subscription: true, + }).map((stage) => ({ stage })) + ); + } +} diff --git a/libs/metering/src/lib/metering-consumer.service.spec.ts b/libs/metering/src/lib/metering-consumer.service.spec.ts index 5fd0fda..b3d7a5d 100644 --- a/libs/metering/src/lib/metering-consumer.service.spec.ts +++ b/libs/metering/src/lib/metering-consumer.service.spec.ts @@ -6,6 +6,7 @@ import type { PubSub } from '@google-cloud/pubsub'; import { Logger } from '@nestjs/common'; import type { LoggerService } from '@nestjs/common'; import { Test } from '@nestjs/testing'; +import { Registry } from '@prometheus-io/client'; import { MeteringConfigurationManager, @@ -16,6 +17,7 @@ import { StatsDService, type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; import { MockMeteringPubSubConfig, @@ -24,12 +26,14 @@ import { import { MeteringConsumerService } from './metering-consumer.service'; import { MeteringEventsManager } from './metering-events.manager'; import { ClickHouseError, UsageCountersError } from './metering.error'; +import { ConsumerMetrics } from './metering-consumer.metrics'; import type { DedupeStatus, PubSubMessage } from './metering.types'; import { UsageCountersManager } from './usage-counters.manager'; import { MeteringPubSubClient } from './metering-pubsub.provider'; import { dayCountersExpireAt } from './utils/counterExpiry'; import { hashEventId } from './utils/hashEventId'; import { dayCountersKey, dedupeKey, sessionKey } from './utils/redisKeys'; +import { incrementedMetricValues, metricValues } from '../testing'; jest.mock('@sentry/nestjs', () => ({ captureException: jest.fn(), @@ -89,6 +93,7 @@ describe('MeteringConsumerService', () => { Pick >; let statsd: jest.Mocked>; + let registry: Registry; let logger: jest.Mocked>; let subscriptionOn: jest.Mock; let subscriptionClose: jest.Mock; @@ -121,6 +126,7 @@ describe('MeteringConsumerService', () => { ), }; statsd = { increment: jest.fn() }; + registry = new Registry(); logger = { error: jest.fn() }; const pubsub: Pick = { @@ -146,6 +152,8 @@ describe('MeteringConsumerService', () => { useValue: meteringConfigurationManager, }, { provide: StatsDService, useValue: statsd }, + { provide: PrometheusRegistry, useValue: registry }, + ConsumerMetrics, { provide: Logger, useValue: logger }, ], }).compile(); @@ -240,6 +248,29 @@ describe('MeteringConsumerService', () => { ); }); + it('records a received message in Prometheus', async () => { + service.handleMessage(messageFor(WIRE_EVENT)); + + expect( + await metricValues(registry, 'metering_consumer_received_total') + ).toEqual([{ value: 1, labels: {} }]); + }); + + it('records an invalid message as an error in Prometheus', async () => { + service.handleMessage({ + data: Buffer.from('{not json', 'utf8'), + ack: jest.fn(), + nack: jest.fn(), + } as PubSubMessage); + + expect( + await incrementedMetricValues( + registry, + 'metering_consumer_errors_total' + ) + ).toEqual([{ value: 1, labels: { stage: 'invalid' } }]); + }); + it('acks and drops a message that fails schema validation', () => { const message = messageFor({ ...WIRE_EVENT, amount: -1 }); @@ -335,6 +366,17 @@ describe('MeteringConsumerService', () => { ); }); + it('records an already-stored duplicate in Prometheus', async () => { + usageCountersManager.claim.mockResolvedValue(['duplicate']); + + service.handleMessage(messageFor(WIRE_EVENT)); + await service.flushNow(); + + expect( + await metricValues(registry, 'metering_consumer_duplicate_total') + ).toEqual([{ value: 1, labels: {} }]); + }); + it('nacks an event whose key is claimed by an unfinished batch', async () => { usageCountersManager.claim.mockResolvedValue(['pending']); const message = messageFor(WIRE_EVENT); @@ -351,6 +393,17 @@ describe('MeteringConsumerService', () => { ); }); + it('records an event claimed by an unfinished batch in Prometheus', async () => { + usageCountersManager.claim.mockResolvedValue(['pending']); + + service.handleMessage(messageFor(WIRE_EVENT)); + await service.flushNow(); + + expect( + await metricValues(registry, 'metering_consumer_pending_total') + ).toEqual([{ value: 1, labels: {} }]); + }); + it('nacks the whole batch and inserts nothing when redis is down', async () => { usageCountersManager.claim.mockRejectedValue( new UsageCountersError('claim', new Error('connection closed')) @@ -370,6 +423,22 @@ describe('MeteringConsumerService', () => { ); }); + it('records a dedupe failure in Prometheus', async () => { + usageCountersManager.claim.mockRejectedValue( + new UsageCountersError('claim', new Error('connection closed')) + ); + + service.handleMessage(messageFor(WIRE_EVENT)); + await service.flushNow(); + + expect( + await incrementedMetricValues( + registry, + 'metering_consumer_errors_total' + ) + ).toEqual([{ value: 1, labels: { stage: 'dedupe' } }]); + }); + it('confirms the claims with the counter writes after a successful insert', async () => { service.handleMessage(messageFor(WIRE_EVENT)); await service.flushNow(); @@ -433,6 +502,22 @@ describe('MeteringConsumerService', () => { ); }); + it('records a confirm failure in Prometheus', async () => { + usageCountersManager.confirm.mockRejectedValue( + new UsageCountersError('confirm', new Error('connection closed')) + ); + + service.handleMessage(messageFor(WIRE_EVENT)); + await service.flushNow(); + + expect( + await incrementedMetricValues( + registry, + 'metering_consumer_errors_total' + ) + ).toEqual([{ value: 1, labels: { stage: 'confirm' } }]); + }); + it('counts only inserted survivors in the inserted metric', async () => { usageCountersManager.claim.mockResolvedValue(['claimed', 'duplicate']); @@ -477,6 +562,53 @@ describe('MeteringConsumerService', () => { ); }); + it('records only inserted survivors in Prometheus', async () => { + usageCountersManager.claim.mockResolvedValue(['claimed', 'duplicate']); + + service.handleMessage(messageFor(WIRE_EVENT)); + service.handleMessage( + messageFor({ ...WIRE_EVENT, id: 'event-2', amount: 7 }) + ); + await service.flushNow(); + + expect( + await metricValues(registry, 'metering_consumer_inserted_total') + ).toEqual([{ value: 1, labels: { client_id: 'vpn', slug: 'tokens' } }]); + }); + + it('records the inserted amount of survivors in Prometheus', async () => { + usageCountersManager.claim.mockResolvedValue(['claimed', 'duplicate']); + + service.handleMessage(messageFor(WIRE_EVENT)); + service.handleMessage( + messageFor({ ...WIRE_EVENT, id: 'event-2', amount: 7 }) + ); + await service.flushNow(); + + expect( + await metricValues(registry, 'metering_consumer_inserted_amount_total') + ).toEqual([{ value: 5, labels: { client_id: 'vpn', slug: 'tokens' } }]); + }); + + it('records inserted counts separately for each client and slug in Prometheus', async () => { + service.handleMessage(messageFor(WIRE_EVENT)); + service.handleMessage( + messageFor({ ...WIRE_EVENT, id: 'event-2', slug: 'bandwidth' }) + ); + service.handleMessage( + messageFor({ ...WIRE_EVENT, id: 'event-3', clientId: 'relay' }) + ); + await service.flushNow(); + + expect( + await metricValues(registry, 'metering_consumer_inserted_total') + ).toEqual([ + { value: 1, labels: { client_id: 'vpn', slug: 'tokens' } }, + { value: 1, labels: { client_id: 'vpn', slug: 'bandwidth' } }, + { value: 1, labels: { client_id: 'relay', slug: 'tokens' } }, + ]); + }); + it('reports inserted counts and amounts separately for each slug', async () => { service.handleMessage(messageFor(WIRE_EVENT)); service.handleMessage( @@ -562,6 +694,17 @@ describe('MeteringConsumerService', () => { ); }); + it('records a batch nacked while ingest is paused in Prometheus', async () => { + usageCountersManager.isIngestAllowed.mockResolvedValue(false); + + service.handleMessage(messageFor(WIRE_EVENT)); + await service.flushNow(); + + expect( + await metricValues(registry, 'metering_consumer_paused_total') + ).toEqual([{ value: 1, labels: {} }]); + }); + it('nacks the batch when the ingest check fails', async () => { usageCountersManager.isIngestAllowed.mockRejectedValue( new UsageCountersError( @@ -580,6 +723,25 @@ describe('MeteringConsumerService', () => { 'metering.consumer.dedupe_error' ); }); + + it('records a failed ingest check as a dedupe error in Prometheus', async () => { + usageCountersManager.isIngestAllowed.mockRejectedValue( + new UsageCountersError( + 'isIngestAllowed', + new Error('connection closed') + ) + ); + + service.handleMessage(messageFor(WIRE_EVENT)); + await service.flushNow(); + + expect( + await incrementedMetricValues( + registry, + 'metering_consumer_errors_total' + ) + ).toEqual([{ value: 1, labels: { stage: 'dedupe' } }]); + }); }); describe('meter lookup failure', () => { @@ -610,6 +772,18 @@ describe('MeteringConsumerService', () => { 'metering.consumer.meter_error' ); }); + + it('records the failure as a meter error in Prometheus', async () => { + service.handleMessage(messageFor(WIRE_EVENT)); + await service.flushNow(); + + expect( + await incrementedMetricValues( + registry, + 'metering_consumer_errors_total' + ) + ).toEqual([{ value: 1, labels: { stage: 'meter' } }]); + }); }); describe('meter lookup failure for one slug', () => { @@ -697,6 +871,35 @@ describe('MeteringConsumerService', () => { expect(metrics).not.toContain('metering.consumer.inserted_amount'); }); + it('records no inserted count in Prometheus when the insert fails', async () => { + meteringEventsManager.insertEvents.mockRejectedValue( + new ClickHouseError('insert', new Error('down')) + ); + + service.handleMessage(messageFor(WIRE_EVENT)); + await service.flushNow(); + + expect( + await metricValues(registry, 'metering_consumer_inserted_total') + ).toEqual([]); + }); + + it('records the insert failure in Prometheus', async () => { + meteringEventsManager.insertEvents.mockRejectedValue( + new ClickHouseError('insert', new Error('down')) + ); + + service.handleMessage(messageFor(WIRE_EVENT)); + await service.flushNow(); + + expect( + await incrementedMetricValues( + registry, + 'metering_consumer_errors_total' + ) + ).toEqual([{ value: 1, labels: { stage: 'insert' } }]); + }); + it('releases the claims and nacks the batch when the insert fails', async () => { meteringEventsManager.insertEvents.mockRejectedValue( new ClickHouseError('insert', new Error('down')) diff --git a/libs/metering/src/lib/metering-consumer.service.ts b/libs/metering/src/lib/metering-consumer.service.ts index 4e29626..0209235 100644 --- a/libs/metering/src/lib/metering-consumer.service.ts +++ b/libs/metering/src/lib/metering-consumer.service.ts @@ -22,6 +22,10 @@ import { type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { + type ConsumerErrorStage, + ConsumerMetrics, +} from './metering-consumer.metrics'; import { MeteringEventsManager } from './metering-events.manager'; import { MeteringPubSubConfig } from './metering-pubsub.config'; import { MeteringPubSubClient } from './metering-pubsub.provider'; @@ -74,6 +78,7 @@ export class MeteringConsumerService private readonly meteringEventsManager: MeteringEventsManager, private readonly meteringConfigurationManager: MeteringConfigurationManager, @Inject(StatsDService) private readonly statsd: StatsD, + private readonly metrics: ConsumerMetrics, @Inject(Logger) private readonly logger: LoggerService ) { this.subscription = pubsub.subscription( @@ -88,7 +93,8 @@ export class MeteringConsumerService maxSize: this.meteringPubSubConfig.consumerBatchSize, flushIntervalMs: this.meteringPubSubConfig.consumerFlushIntervalMs, onFlush: (batch) => this.processBatch(batch), - onError: (err) => this.report('metering.consumer.flush_error', err), + onError: (err) => + this.report('metering.consumer.flush_error', 'flush', err), }); } @@ -97,7 +103,7 @@ export class MeteringConsumerService this.handleMessage(message) ); this.subscription.on('error', (err: Error) => { - this.report('metering.consumer.subscription_error', err); + this.report('metering.consumer.subscription_error', 'subscription', err); }); this.started = true; } @@ -123,12 +129,13 @@ export class MeteringConsumerService try { event = parseWireEvent(message.data); } catch (err) { - this.report('metering.consumer.invalid', err); + this.report('metering.consumer.invalid', 'invalid', err); message.ack(); return; } this.statsd.increment('metering.consumer.received'); + this.metrics.received.inc(); const eventIdHash = hashEventId(event.id); this.buffer.push({ message, @@ -147,7 +154,7 @@ export class MeteringConsumerService try { ingestAllowed = await this.usageCountersManager.isIngestAllowed(); } catch (err) { - this.nackAll(batch, 'metering.consumer.dedupe_error', err); + this.nackAll(batch, 'metering.consumer.dedupe_error', 'dedupe', err); return; } if (!ingestAllowed) { @@ -155,6 +162,7 @@ export class MeteringConsumerService message.nack(); } this.statsd.increment('metering.consumer.paused', batch.length); + this.metrics.paused.inc(batch.length); return; } @@ -162,7 +170,7 @@ export class MeteringConsumerService try { classified = await this.classify(batch); } catch (err) { - this.nackAll(batch, 'metering.consumer.dedupe_error', err); + this.nackAll(batch, 'metering.consumer.dedupe_error', 'dedupe', err); return; } const { fresh, duplicates, pending } = classified; @@ -172,6 +180,7 @@ export class MeteringConsumerService message.nack(); } this.statsd.increment('metering.consumer.pending', pending.length); + this.metrics.pending.inc(pending.length); } if (fresh.length > 0) { @@ -183,6 +192,7 @@ export class MeteringConsumerService message.ack(); } this.statsd.increment('metering.consumer.duplicate', duplicates.length); + this.metrics.duplicates.inc(duplicates.length); } } @@ -223,7 +233,7 @@ export class MeteringConsumerService for (const [slug, err] of failuresBySlug) { const unavailable = fresh.filter(({ event }) => event.slug === slug); await this.releaseClaims(unavailable.map((buffered) => buffered.key)); - this.nackAll(unavailable, 'metering.consumer.meter_error', err); + this.nackAll(unavailable, 'metering.consumer.meter_error', 'meter', err); } const insertable = fresh.filter( @@ -248,7 +258,7 @@ export class MeteringConsumerService await this.meteringEventsManager.insertEvents(events); } catch (err) { await this.releaseClaims(keys); - this.nackAll(insertable, 'metering.consumer.insert_error', err); + this.nackAll(insertable, 'metering.consumer.insert_error', 'insert', err); return; } @@ -288,7 +298,7 @@ export class MeteringConsumerService try { await this.usageCountersManager.confirm(keys, counterWrites); } catch (err) { - this.report('metering.consumer.confirm_error', err); + this.report('metering.consumer.confirm_error', 'confirm', err); } } @@ -319,18 +329,23 @@ export class MeteringConsumerService const tags = { clientId, slug }; this.statsd.increment('metering.consumer.inserted', count, tags); this.statsd.increment('metering.consumer.inserted_amount', amount, tags); + const labels = { client_id: clientId, slug }; + this.metrics.inserted.inc(labels, count); + this.metrics.insertedAmount.inc(labels, amount); } } private nackAll( batch: BufferedMessage[], metric: string, + stage: ConsumerErrorStage, err: unknown ): void { for (const { message } of batch) { message.nack(); } this.statsd.increment(metric); + this.metrics.errors.inc({ stage }); Sentry.withScope((scope) => { scope.setExtra('batchSize', batch.length); Sentry.captureException(err); @@ -338,8 +353,13 @@ export class MeteringConsumerService this.logger.error(err); } - private report(metric: string, err: unknown): void { + private report( + metric: string, + stage: ConsumerErrorStage, + err: unknown + ): void { this.statsd.increment(metric); + this.metrics.errors.inc({ stage }); Sentry.captureException(err); this.logger.error(err); } diff --git a/libs/metering/src/lib/metering-events.manager.in.spec.ts b/libs/metering/src/lib/metering-events.manager.in.spec.ts index c53c86c..41891fd 100644 --- a/libs/metering/src/lib/metering-events.manager.in.spec.ts +++ b/libs/metering/src/lib/metering-events.manager.in.spec.ts @@ -4,6 +4,7 @@ import 'reflect-metadata'; +import { Registry } from '@prometheus-io/client'; import { z } from 'zod'; import { StatsD } from '@entitlements/shared/metrics/statsd'; @@ -20,6 +21,7 @@ import { } from '../testing'; import { MeteringEventsRepository } from './metering-events.repository'; import { ClickHouseError } from './metering.error'; +import { ClickHouseMetrics } from './clickhouse.metrics'; import { MeteringEventsManager } from './metering-events.manager'; import { hashEventId } from './utils/hashEventId'; @@ -260,6 +262,7 @@ describeClickHouse('MeteringEventsManager against a real ClickHouse', () => { maxBytesBeforeExternalGroupBy: 1, }, new StatsD({ mock: true }), + new ClickHouseMetrics(new Registry()), integrationClickHouseRateLimiters() ) ) diff --git a/libs/metering/src/lib/metering-metrics-scheduler.service.spec.ts b/libs/metering/src/lib/metering-metrics-scheduler.service.spec.ts index 9e125a4..367cfda 100644 --- a/libs/metering/src/lib/metering-metrics-scheduler.service.spec.ts +++ b/libs/metering/src/lib/metering-metrics-scheduler.service.spec.ts @@ -7,17 +7,22 @@ import type { LoggerService } from '@nestjs/common'; import { InMemoryLockStore, LocksModule, LocksStorage } from '@nestjs/locks'; import { ScheduleModule, SchedulerRegistry } from '@nestjs/schedule'; import { Test, type TestingModule } from '@nestjs/testing'; +import { Registry } from '@prometheus-io/client'; import { StatsDService, type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; import { MeteringMetricsSchedulerService } from './metering-metrics-scheduler.service'; import { MeteringMetricsService } from './metering-metrics.service'; import { MeteringMetricsSchedulerConfig } from './metering-scheduler.config'; import { MeteringSchedulerService } from './metering-scheduler.service'; +import { MetricsReportMetrics } from './metering-metrics.metrics'; +import { SchedulerMetrics } from './metering-scheduler.metrics'; import type { MetricsReportAllResult } from './metering.types'; +import { metricValues } from '../testing'; jest.mock('@nestjs/schedule', () => jest @@ -53,6 +58,9 @@ describe('MeteringMetricsSchedulerService', () => { { provide: MeteringMetricsSchedulerConfig, useValue: config }, { provide: MeteringMetricsService, useValue: metricsService }, { provide: StatsDService, useValue: statsd }, + { provide: PrometheusRegistry, useValue: new Registry() }, + MetricsReportMetrics, + SchedulerMetrics, { provide: Logger, useValue: logger }, ], }).compile(); @@ -161,6 +169,24 @@ describe('MeteringMetricsSchedulerService', () => { { job: 'metrics', reason: 'ownership-unavailable' } ); }); + + it('clears the metrics gauges', async () => { + moduleRef + .get(MetricsReportMetrics) + .meterLimit.set( + { client_id: 'vpn', slug: 'tokens', unit: 'tokens' }, + 100 + ); + + await service.reportMetrics(); + + expect( + await metricValues( + moduleRef.get(PrometheusRegistry), + 'metering_meter_limit' + ) + ).toEqual([]); + }); }); describe('when a report is still running on another instance', () => { @@ -182,6 +208,29 @@ describe('MeteringMetricsSchedulerService', () => { { job: 'metrics', reason: 'run-lock-unavailable' } ); }); + + it('keeps the metrics gauges', async () => { + moduleRef + .get(MetricsReportMetrics) + .meterLimit.set( + { client_id: 'vpn', slug: 'tokens', unit: 'tokens' }, + 100 + ); + + await service.reportMetrics(); + + expect( + await metricValues( + moduleRef.get(PrometheusRegistry), + 'metering_meter_limit' + ) + ).toEqual([ + { + value: 100, + labels: { client_id: 'vpn', slug: 'tokens', unit: 'tokens' }, + }, + ]); + }); }); describe('when the lock store fails', () => { diff --git a/libs/metering/src/lib/metering-metrics-scheduler.service.ts b/libs/metering/src/lib/metering-metrics-scheduler.service.ts index acde482..fd515e4 100644 --- a/libs/metering/src/lib/metering-metrics-scheduler.service.ts +++ b/libs/metering/src/lib/metering-metrics-scheduler.service.ts @@ -18,6 +18,7 @@ import { MeteringSchedulerService, SCHEDULED_AT_BOOTSTRAP, } from './metering-scheduler.service'; +import { MetricsReportMetrics } from './metering-metrics.metrics'; @Injectable() export class MeteringMetricsSchedulerService implements OnApplicationBootstrap { @@ -25,13 +26,15 @@ export class MeteringMetricsSchedulerService implements OnApplicationBootstrap { private readonly meteringMetricsSchedulerConfig: MeteringMetricsSchedulerConfig, private readonly meteringSchedulerService: MeteringSchedulerService, private readonly meteringMetricsService: MeteringMetricsService, + private readonly metricsReportMetrics: MetricsReportMetrics, @Inject(Logger) private readonly logger: LoggerService ) {} onApplicationBootstrap(): void { this.meteringSchedulerService.schedule( 'metrics', - this.meteringMetricsSchedulerConfig.cron + this.meteringMetricsSchedulerConfig.cron, + () => this.metricsReportMetrics.resetGauges() ); } diff --git a/libs/metering/src/lib/metering-metrics.metrics.ts b/libs/metering/src/lib/metering-metrics.metrics.ts new file mode 100644 index 0000000..a5f850d --- /dev/null +++ b/libs/metering/src/lib/metering-metrics.metrics.ts @@ -0,0 +1,64 @@ +/* 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 } from '@nestjs/common'; +import type { Registry } from '@prometheus-io/client'; + +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; + +import { counter, gauge, jobHistogram } from './utils/metrics'; + +@Injectable() +export class MetricsReportMetrics { + readonly reports; + readonly duration; + readonly allDuration; + readonly meterLimit; + readonly activeSubjectsToday; + readonly notifiedSubjects; + + constructor(@Inject(PrometheusRegistry) registry: Registry) { + this.reports = counter( + registry, + 'metering_metrics_report_total', + 'Meter metrics reports', + ['outcome', 'slug'] + ); + this.duration = jobHistogram( + registry, + 'metering_metrics_report_duration_seconds', + 'Duration of one meter metrics report', + ['slug'] + ); + this.allDuration = jobHistogram( + registry, + 'metering_metrics_report_all_duration_seconds', + 'Duration of a metrics report over every meter' + ); + this.meterLimit = gauge( + registry, + 'metering_meter_limit', + 'Configured meter limit', + ['client_id', 'slug', 'unit'] + ); + this.activeSubjectsToday = gauge( + registry, + 'metering_active_subjects_today', + 'Subjects with usage today', + ['client_id', 'slug'] + ); + this.notifiedSubjects = gauge( + registry, + 'metering_notified_subjects', + 'Subjects notified for a threshold in the current window', + ['client_id', 'slug', 'threshold'] + ); + } + + resetGauges(): void { + this.meterLimit.reset(); + this.activeSubjectsToday.reset(); + this.notifiedSubjects.reset(); + } +} diff --git a/libs/metering/src/lib/metering-metrics.service.spec.ts b/libs/metering/src/lib/metering-metrics.service.spec.ts index 2fb53d1..a1cd629 100644 --- a/libs/metering/src/lib/metering-metrics.service.spec.ts +++ b/libs/metering/src/lib/metering-metrics.service.spec.ts @@ -5,6 +5,7 @@ import { Logger } from '@nestjs/common'; import type { LoggerService } from '@nestjs/common'; import { Test } from '@nestjs/testing'; +import { Registry } from '@prometheus-io/client'; import { MeterBySlugResultUtil, @@ -16,11 +17,14 @@ import { StatsDService, type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; import { ClickHouseError } from './metering.error'; import { MeteringMetricsManager } from './metering-metrics.manager'; import { MeteringMetricsService } from './metering-metrics.service'; import { MeteringSweepManager } from './metering-sweep.manager'; +import { MetricsReportMetrics } from './metering-metrics.metrics'; +import { metricValues } from '../testing'; const CLIENT_ID = 'vpn'; const SLUG = 'tokens'; @@ -42,6 +46,7 @@ describe('MeteringMetricsService', () => { Pick >; let statsd: jest.Mocked>; + let registry: Registry; let logger: jest.Mocked>; function utilFor(raw: StrapiMeterRaw): MeterBySlugResultUtil { @@ -64,9 +69,17 @@ describe('MeteringMetricsService', () => { return statsd.gauge.mock.calls.filter(([metric]) => metric === name); } + async function histogramCount(name: string) { + return (await metricValues(registry, name)).find( + ({ metricName }) => metricName === `${name}_count` + ); + } + const params = { clientId: CLIENT_ID, slug: SLUG }; + const LABELS = { client_id: CLIENT_ID, slug: SLUG }; beforeEach(async () => { + registry = new Registry(); meteringConfigurationManager = { getMeterResultUtil: jest.fn().mockResolvedValue(utilFor(meter())), }; @@ -93,6 +106,8 @@ describe('MeteringMetricsService', () => { { provide: MeteringMetricsManager, useValue: meteringMetricsManager }, { provide: MeteringSweepManager, useValue: meteringSweepManager }, { provide: StatsDService, useValue: statsd }, + { provide: PrometheusRegistry, useValue: registry }, + MetricsReportMetrics, { provide: Logger, useValue: logger }, ], }).compile(); @@ -242,6 +257,12 @@ describe('MeteringMetricsService', () => { expect(statsd.gauge).not.toHaveBeenCalled(); }); + + it('sets no Prometheus gauges', async () => { + await service.report(params, NOW); + + expect(await metricValues(registry, 'metering_meter_limit')).toEqual([]); + }); }); describe('gauges', () => { @@ -278,6 +299,33 @@ describe('MeteringMetricsService', () => { ]); }); + it('sets the meter limit gauge labelled with its unit in Prometheus', async () => { + await service.report(params, NOW); + + expect(await metricValues(registry, 'metering_meter_limit')).toEqual([ + { value: 100, labels: { ...LABELS, unit: 'tokens' } }, + ]); + }); + + it('sets the subjects-today gauge in Prometheus', async () => { + await service.report(params, NOW); + + expect( + await metricValues(registry, 'metering_active_subjects_today') + ).toEqual([{ value: 42, labels: LABELS }]); + }); + + it('sets the notified-subjects gauge for each threshold in Prometheus', async () => { + await service.report(params, NOW); + + expect( + await metricValues(registry, 'metering_notified_subjects') + ).toEqual([ + { value: 12, labels: { ...LABELS, threshold: '80' } }, + { value: 3, labels: { ...LABELS, threshold: '100' } }, + ]); + }); + it('keeps the gauges of two clients that share a slug apart', async () => { await service.report(params, NOW); await service.report({ clientId: 'relay', slug: SLUG }, NOW); @@ -291,6 +339,18 @@ describe('MeteringMetricsService', () => { ], ]); }); + + it('keeps the Prometheus gauges of two clients that share a slug apart', async () => { + await service.report(params, NOW); + await service.report({ clientId: 'relay', slug: SLUG }, NOW); + + expect( + await metricValues(registry, 'metering_active_subjects_today') + ).toEqual([ + { value: 42, labels: LABELS }, + { value: 42, labels: { client_id: 'relay', slug: SLUG } }, + ]); + }); }); describe('outcome metric', () => { @@ -303,6 +363,14 @@ describe('MeteringMetricsService', () => { }); }); + it('records a reported meter by slug in Prometheus', async () => { + await service.report(params, NOW); + + expect( + await metricValues(registry, 'metering_metrics_report_total') + ).toEqual([{ value: 1, labels: { outcome: 'reported', slug: SLUG } }]); + }); + it('counts a meter that is not configured', async () => { meteringConfigurationManager.getMeterResultUtil.mockResolvedValue( new MeterBySlugResultUtil({ meters: [] }, SLUG) @@ -316,6 +384,20 @@ describe('MeteringMetricsService', () => { }); }); + it('records a meter that is not configured in Prometheus', async () => { + meteringConfigurationManager.getMeterResultUtil.mockResolvedValue( + new MeterBySlugResultUtil({ meters: [] }, SLUG) + ); + + await service.report(params, NOW); + + expect( + await metricValues(registry, 'metering_metrics_report_total') + ).toEqual([ + { value: 1, labels: { outcome: 'meter-not-configured', slug: SLUG } }, + ]); + }); + it('rethrows when a ClickHouse query fails', async () => { meteringMetricsManager.findActiveSubjectCount.mockRejectedValue( new ClickHouseError('query', new Error('timeout')) @@ -339,6 +421,18 @@ describe('MeteringMetricsService', () => { }); }); + it('records an error outcome in Prometheus when a ClickHouse query fails', async () => { + meteringMetricsManager.findNotifiedSubjectCounts.mockRejectedValue( + new ClickHouseError('query', new Error('timeout')) + ); + + await service.report(params, NOW).catch(() => undefined); + + expect( + await metricValues(registry, 'metering_metrics_report_total') + ).toEqual([{ value: 1, labels: { outcome: 'error', slug: SLUG } }]); + }); + it('rethrows when the meter lookup fails', async () => { meteringConfigurationManager.getMeterResultUtil.mockRejectedValue( new Error('strapi unavailable') @@ -385,6 +479,34 @@ describe('MeteringMetricsService', () => { { slug: SLUG } ); }); + + it('times the meter by slug in Prometheus', async () => { + await service.report(params, NOW); + + expect( + await histogramCount('metering_metrics_report_duration_seconds') + ).toEqual({ + metricName: 'metering_metrics_report_duration_seconds_count', + value: 1, + labels: { slug: SLUG }, + }); + }); + + it('times a meter that failed in Prometheus', async () => { + meteringMetricsManager.findActiveSubjectCount.mockRejectedValue( + new ClickHouseError('query', new Error('timeout')) + ); + + await service.report(params, NOW).catch(() => undefined); + + expect( + await histogramCount('metering_metrics_report_duration_seconds') + ).toEqual({ + metricName: 'metering_metrics_report_duration_seconds_count', + value: 1, + labels: { slug: SLUG }, + }); + }); }); describe('reportAll', () => { @@ -489,6 +611,46 @@ describe('MeteringMetricsService', () => { ); }); + it('times the run in Prometheus', async () => { + await service.reportAll(NOW); + + expect( + await histogramCount('metering_metrics_report_all_duration_seconds') + ).toEqual({ + metricName: 'metering_metrics_report_all_duration_seconds_count', + value: 1, + labels: {}, + }); + }); + + describe('when a threshold is no longer reported', () => { + beforeEach(async () => { + meteringSweepManager.findSweptMeters.mockResolvedValue([params]); + await service.reportAll(NOW); + meteringMetricsManager.findNotifiedSubjectCounts.mockResolvedValue([ + { threshold: 80, subjectCount: 15 }, + ]); + await service.reportAll(NOW); + }); + + it('drops the gauge left over from the previous pass', async () => { + expect( + await metricValues(registry, 'metering_notified_subjects') + ).toEqual([{ value: 15, labels: { ...LABELS, threshold: '80' } }]); + }); + }); + + it('drops the gauges of a meter that is no longer swept', async () => { + meteringSweepManager.findSweptMeters.mockResolvedValueOnce([params]); + await service.reportAll(NOW); + + await service.reportAll(NOW); + + expect( + await metricValues(registry, 'metering_active_subjects_today') + ).toEqual([]); + }); + it('returns zero counts when no meter has been swept', async () => { await expect(service.reportAll(NOW)).resolves.toEqual({ total: 0, diff --git a/libs/metering/src/lib/metering-metrics.service.ts b/libs/metering/src/lib/metering-metrics.service.ts index a0b88c5..a646a63 100644 --- a/libs/metering/src/lib/metering-metrics.service.ts +++ b/libs/metering/src/lib/metering-metrics.service.ts @@ -15,6 +15,7 @@ import { type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { MetricsReportMetrics } from './metering-metrics.metrics'; import type { MeterKey, MetricsReportAllResult, @@ -32,12 +33,14 @@ export class MeteringMetricsService { private readonly meteringMetricsManager: MeteringMetricsManager, private readonly meteringSweepManager: MeteringSweepManager, @Inject(StatsDService) private readonly statsd: StatsD, + private readonly metrics: MetricsReportMetrics, @Inject(Logger) private readonly logger: LoggerService ) {} async reportAll(now: Date = new Date()): Promise { const startedAt = Date.now(); const meters = await this.meteringSweepManager.findSweptMeters(); + this.metrics.resetGauges(); let failed = 0; for (const meter of meters) { @@ -59,6 +62,7 @@ export class MeteringMetricsService { 'metering.metrics_report_all.duration', Date.now() - startedAt ); + this.metrics.allDuration.observe((Date.now() - startedAt) / 1000); return { total: meters.length, failed }; } @@ -92,6 +96,11 @@ export class MeteringMetricsService { Date.now() - startedAt, { slug: params.slug } ); + this.metrics.reports.inc({ outcome, slug: params.slug }); + this.metrics.duration.observe( + { slug: params.slug }, + (Date.now() - startedAt) / 1000 + ); } } @@ -165,11 +174,18 @@ export class MeteringMetricsService { activeSubjectCountToday, tags ); + const labels = { client_id: params.clientId, slug: params.slug }; + this.metrics.meterLimit.set({ ...labels, unit: meter.unit }, meter.limit); + this.metrics.activeSubjectsToday.set(labels, activeSubjectCountToday); for (const { threshold, subjectCount } of notifiedSubjectCounts) { this.statsd.gauge('metering.metrics.notified_subjects', subjectCount, { ...tags, threshold: String(threshold), }); + this.metrics.notifiedSubjects.set( + { ...labels, threshold: String(threshold) }, + subjectCount + ); } } } diff --git a/libs/metering/src/lib/metering-publisher.manager.spec.ts b/libs/metering/src/lib/metering-publisher.manager.spec.ts index ed347bd..ef483b3 100644 --- a/libs/metering/src/lib/metering-publisher.manager.spec.ts +++ b/libs/metering/src/lib/metering-publisher.manager.spec.ts @@ -4,11 +4,13 @@ import type { PubSub } from '@google-cloud/pubsub'; import { Test } from '@nestjs/testing'; +import { Registry } from '@prometheus-io/client'; import { StatsDService, type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; import { MockMeteringPubSubConfig, @@ -16,8 +18,10 @@ import { } from './metering-pubsub.config'; import { MeteringPublisherManager } from './metering-publisher.manager'; import { PublishError } from './metering.error'; +import { UsageMetrics } from './usage.metrics'; import type { MeteringWireEvent } from './metering.schema'; import { MeteringPubSubClient } from './metering-pubsub.provider'; +import { metricValues } from '../testing'; const EVENT: MeteringWireEvent = { id: 'event-1', @@ -33,8 +37,10 @@ describe('MeteringPublisherManager', () => { let publishMessage: jest.Mock; let topic: jest.Mock; let statsd: jest.Mocked>; + let registry: Registry; beforeEach(async () => { + registry = new Registry(); publishMessage = jest.fn().mockResolvedValue('message-id'); topic = jest.fn().mockReturnValue({ publishMessage }); statsd = { increment: jest.fn() }; @@ -47,6 +53,8 @@ describe('MeteringPublisherManager', () => { { provide: MeteringPubSubConfig, useValue: MockMeteringPubSubConfig }, { provide: MeteringPubSubClient, useValue: pubsub }, { provide: StatsDService, useValue: statsd }, + { provide: PrometheusRegistry, useValue: registry }, + UsageMetrics, ], }).compile(); @@ -108,6 +116,22 @@ describe('MeteringPublisherManager', () => { ); }); + it('records a successful publish in Prometheus', async () => { + await manager.publish(EVENT); + + expect( + await metricValues(registry, 'metering_publisher_published_total') + ).toEqual([{ value: 1, labels: {} }]); + }); + + it('does not record a successful publish as an error', async () => { + await manager.publish(EVENT); + + expect( + await metricValues(registry, 'metering_publisher_errors_total') + ).toEqual([{ value: 0, labels: {} }]); + }); + it('wraps a publish failure in PublishError', async () => { publishMessage.mockRejectedValue(new Error('pubsub unavailable')); @@ -123,6 +147,16 @@ describe('MeteringPublisherManager', () => { ); }); + it('records a failed publish in Prometheus', async () => { + publishMessage.mockRejectedValue(new Error('pubsub unavailable')); + + await manager.publish(EVENT).catch(() => undefined); + + expect( + await metricValues(registry, 'metering_publisher_errors_total') + ).toEqual([{ value: 1, labels: {} }]); + }); + it('wraps a non-Error rejection in PublishError', async () => { publishMessage.mockRejectedValue('boom'); diff --git a/libs/metering/src/lib/metering-publisher.manager.ts b/libs/metering/src/lib/metering-publisher.manager.ts index 64273f2..97466ab 100644 --- a/libs/metering/src/lib/metering-publisher.manager.ts +++ b/libs/metering/src/lib/metering-publisher.manager.ts @@ -10,6 +10,7 @@ import { type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { UsageMetrics } from './usage.metrics'; import { PublishError } from './metering.error'; import type { MeteringWireEvent } from './metering.schema'; import { MeteringPubSubConfig } from './metering-pubsub.config'; @@ -25,7 +26,8 @@ export class MeteringPublisherManager { constructor( meteringPubSubConfig: MeteringPubSubConfig, @Inject(MeteringPubSubClient) pubsub: PubSub, - @Inject(StatsDService) private readonly statsd: StatsD + @Inject(StatsDService) private readonly statsd: StatsD, + private readonly metrics: UsageMetrics ) { this.topic = pubsub.topic(meteringPubSubConfig.topicName, { batching: { @@ -40,8 +42,10 @@ export class MeteringPublisherManager { try { await this.topic.publishMessage({ json: event }); this.statsd.increment('metering.publisher.published'); + this.metrics.published.inc(); } catch (err) { this.statsd.increment('metering.publisher.publish_error'); + this.metrics.publishErrors.inc(); throw new PublishError(toError(err)); } } diff --git a/libs/metering/src/lib/metering-scheduler.metrics.spec.ts b/libs/metering/src/lib/metering-scheduler.metrics.spec.ts new file mode 100644 index 0000000..d9a9864 --- /dev/null +++ b/libs/metering/src/lib/metering-scheduler.metrics.spec.ts @@ -0,0 +1,59 @@ +/* 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 { Registry } from '@prometheus-io/client'; + +import { SchedulerMetrics } from './metering-scheduler.metrics'; +import { metricValues, zeroMetricValues } from '../testing'; + +describe('SchedulerMetrics', () => { + let registry: Registry; + + beforeEach(() => { + registry = new Registry(); + }); + + describe('initializeJob', () => { + beforeEach(() => { + new SchedulerMetrics(registry).initializeJob('sweep'); + }); + + it('starts each run outcome of the job at zero', async () => { + expect( + await metricValues(registry, 'metering_scheduler_runs_total') + ).toEqual( + zeroMetricValues([ + { job: 'sweep', outcome: 'ok' }, + { job: 'sweep', outcome: 'failed' }, + { job: 'sweep', outcome: 'error' }, + ]) + ); + }); + + it('starts each skip reason of the job at zero', async () => { + expect( + await metricValues(registry, 'metering_scheduler_skips_total') + ).toEqual( + zeroMetricValues([ + { job: 'sweep', reason: 'ownership-unavailable' }, + { job: 'sweep', reason: 'run-lock-unavailable' }, + { job: 'sweep', reason: 'shutdown' }, + ]) + ); + }); + + it('starts lost locks of the job ownership and run locks at zero', async () => { + expect( + await metricValues(registry, 'metering_scheduler_lock_lost_total') + ).toEqual( + zeroMetricValues([ + { key: 'sweep:owner', detected_by: 'renewal' }, + { key: 'sweep:owner', detected_by: 'deadline' }, + { key: 'sweep', detected_by: 'renewal' }, + { key: 'sweep', detected_by: 'deadline' }, + ]) + ); + }); + }); +}); diff --git a/libs/metering/src/lib/metering-scheduler.metrics.ts b/libs/metering/src/lib/metering-scheduler.metrics.ts new file mode 100644 index 0000000..4da2e1f --- /dev/null +++ b/libs/metering/src/lib/metering-scheduler.metrics.ts @@ -0,0 +1,68 @@ +/* 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 } from '@nestjs/common'; +import type { LocksJobSkipReason, LocksLockLostEvent } from '@nestjs/locks'; +import type { Registry } from '@prometheus-io/client'; + +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; + +import type { SchedulerJob, SchedulerRunOutcome } from './metering.types'; +import { allOf, counter, initialize } from './utils/metrics'; + +@Injectable() +export class SchedulerMetrics { + readonly runs; + readonly skips; + readonly lockLost; + + constructor(@Inject(PrometheusRegistry) registry: Registry) { + this.runs = counter( + registry, + 'metering_scheduler_runs_total', + 'Scheduled job runs', + ['job', 'outcome'] + ); + this.skips = counter( + registry, + 'metering_scheduler_skips_total', + 'Scheduled job ticks skipped', + ['job', 'reason'] + ); + this.lockLost = counter( + registry, + 'metering_scheduler_lock_lost_total', + 'Scheduler locks lost while held', + ['key', 'detected_by'] + ); + } + + initializeJob(job: SchedulerJob): void { + initialize( + this.runs, + allOf({ + ok: true, + failed: true, + error: true, + }).map((outcome) => ({ job, outcome })) + ); + initialize( + this.skips, + allOf({ + 'ownership-unavailable': true, + 'run-lock-unavailable': true, + shutdown: true, + }).map((reason) => ({ job, reason })) + ); + initialize( + this.lockLost, + [`${job}:owner`, job].flatMap((key) => + allOf({ + renewal: true, + deadline: true, + }).map((detected_by) => ({ key, detected_by })) + ) + ); + } +} diff --git a/libs/metering/src/lib/metering-scheduler.service.spec.ts b/libs/metering/src/lib/metering-scheduler.service.spec.ts index 51b304d..be83b06 100644 --- a/libs/metering/src/lib/metering-scheduler.service.spec.ts +++ b/libs/metering/src/lib/metering-scheduler.service.spec.ts @@ -4,20 +4,28 @@ import { Logger } from '@nestjs/common'; import type { LoggerService } from '@nestjs/common'; -import { LocksEvents, LocksModule } from '@nestjs/locks'; +import { + LocksEvents, + LocksModule, + type LocksJobSkipReason, +} from '@nestjs/locks'; import { SchedulerRegistry } from '@nestjs/schedule'; import { Test, type TestingModule } from '@nestjs/testing'; import { CronJob } from 'cron'; +import { Registry } from '@prometheus-io/client'; import { StatsDService, type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; import { MeteringSchedulerService, SCHEDULED_AT_BOOTSTRAP, } from './metering-scheduler.service'; +import { SchedulerMetrics } from './metering-scheduler.metrics'; +import { incrementedMetricValues, metricValues } from '../testing'; const CONFIGURED_CRON = '0 0 1 2 *'; @@ -27,10 +35,12 @@ describe('MeteringSchedulerService', () => { let registry: SchedulerRegistry; let cronJob: CronJob; let statsd: jest.Mocked>; + let metricsRegistry: Registry; let logger: jest.Mocked>; beforeEach(async () => { statsd = { increment: jest.fn() }; + metricsRegistry = new Registry(); logger = { log: jest.fn(), warn: jest.fn(), debug: jest.fn() }; moduleRef = await Test.createTestingModule({ @@ -39,6 +49,8 @@ describe('MeteringSchedulerService', () => { MeteringSchedulerService, SchedulerRegistry, { provide: StatsDService, useValue: statsd }, + { provide: PrometheusRegistry, useValue: metricsRegistry }, + SchedulerMetrics, { provide: Logger, useValue: logger }, ], }).compile(); @@ -60,6 +72,18 @@ describe('MeteringSchedulerService', () => { }); describe('schedule', () => { + it("starts the job's run counters at zero", async () => { + service.schedule('sweep', CONFIGURED_CRON); + + expect( + await metricValues(metricsRegistry, 'metering_scheduler_runs_total') + ).toEqual([ + { value: 0, labels: { job: 'sweep', outcome: 'ok' } }, + { value: 0, labels: { job: 'sweep', outcome: 'failed' } }, + { value: 0, labels: { job: 'sweep', outcome: 'error' } }, + ]); + }); + it('sets the job to run on the given cron', () => { service.schedule('sweep', CONFIGURED_CRON); @@ -101,6 +125,20 @@ describe('MeteringSchedulerService', () => { } ); + it.each(['ok', 'failed'] as const)( + 'records a run with outcome %s in Prometheus', + async (outcome) => { + await service.run('sweep', async () => outcome); + + expect( + await incrementedMetricValues( + metricsRegistry, + 'metering_scheduler_runs_total' + ) + ).toEqual([{ value: 1, labels: { job: 'sweep', outcome } }]); + } + ); + it('rethrows an error from the job', async () => { const failure = new Error('ClickHouse unavailable'); @@ -119,6 +157,19 @@ describe('MeteringSchedulerService', () => { outcome: 'error', }); }); + + it('records a thrown run as an error in Prometheus', async () => { + await service + .run('sweep', () => Promise.reject(new Error('timeout'))) + .catch(() => undefined); + + expect( + await incrementedMetricValues( + metricsRegistry, + 'metering_scheduler_runs_total' + ) + ).toEqual([{ value: 1, labels: { job: 'sweep', outcome: 'error' } }]); + }); }); describe('lock events', () => { @@ -136,6 +187,77 @@ describe('MeteringSchedulerService', () => { ); }); + it('records a skipped run by job and reason in Prometheus', async () => { + moduleRef.get(LocksEvents).emitJobSkipped({ + type: 'job-skipped', + job: 'MeteringSweepSchedulerService.sweep', + key: 'sweep', + reason: 'ownership-unavailable', + }); + + expect( + await incrementedMetricValues( + metricsRegistry, + 'metering_scheduler_skips_total' + ) + ).toEqual([ + { value: 1, labels: { job: 'sweep', reason: 'ownership-unavailable' } }, + ]); + }); + + describe('when a job was scheduled with a gauge reset', () => { + let resetGauges: jest.Mock; + + const skip = (key: string, reason: LocksJobSkipReason) => + moduleRef.get(LocksEvents).emitJobSkipped({ + type: 'job-skipped', + job: 'MeteringSweepSchedulerService.sweep', + key, + reason, + }); + + beforeEach(() => { + resetGauges = jest.fn(); + service.schedule('sweep', CONFIGURED_CRON, resetGauges); + }); + + it('resets the gauges when another instance owns the job', () => { + skip('sweep', 'ownership-unavailable'); + + expect(resetGauges).toHaveBeenCalledTimes(1); + }); + + it('keeps the gauges when an overlapping run holds the run lock', () => { + skip('sweep', 'run-lock-unavailable'); + + expect(resetGauges).not.toHaveBeenCalled(); + }); + + it('keeps the gauges when another job is owned elsewhere', () => { + skip('metrics', 'ownership-unavailable'); + + expect(resetGauges).not.toHaveBeenCalled(); + }); + }); + + it('records an ownership skip for a key that is not a scheduler job', async () => { + moduleRef.get(LocksEvents).emitJobSkipped({ + type: 'job-skipped', + job: 'Other.job', + key: 'other', + reason: 'ownership-unavailable', + }); + + expect( + await incrementedMetricValues( + metricsRegistry, + 'metering_scheduler_skips_total' + ) + ).toEqual([ + { value: 1, labels: { job: 'other', reason: 'ownership-unavailable' } }, + ]); + }); + describe('when a lock is lost', () => { beforeEach(() => { moduleRef.get(LocksEvents).emit({ @@ -153,6 +275,17 @@ describe('MeteringSchedulerService', () => { ); }); + it('records the lost lock in Prometheus', async () => { + expect( + await incrementedMetricValues( + metricsRegistry, + 'metering_scheduler_lock_lost_total' + ) + ).toEqual([ + { value: 1, labels: { key: 'sweep:owner', detected_by: 'renewal' } }, + ]); + }); + it('logs the lost lock', () => { expect(logger.warn).toHaveBeenCalledWith( 'Lock lost: sweep:owner (renewal)', @@ -170,5 +303,20 @@ describe('MeteringSchedulerService', () => { expect(statsd.increment).not.toHaveBeenCalled(); }); + + it('records nothing in Prometheus for events other than a lost lock', async () => { + moduleRef.get(LocksEvents).emit({ + type: 'leadership-acquired', + key: 'sweep:owner', + fencingToken: 7, + }); + + expect( + await incrementedMetricValues( + metricsRegistry, + 'metering_scheduler_lock_lost_total' + ) + ).toEqual([]); + }); }); }); diff --git a/libs/metering/src/lib/metering-scheduler.service.ts b/libs/metering/src/lib/metering-scheduler.service.ts index b87c1e5..a995b06 100644 --- a/libs/metering/src/lib/metering-scheduler.service.ts +++ b/libs/metering/src/lib/metering-scheduler.service.ts @@ -18,22 +18,30 @@ import { type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { SchedulerMetrics } from './metering-scheduler.metrics'; import type { SchedulerJob, SchedulerRunOutcome } from './metering.types'; export const SCHEDULED_AT_BOOTSTRAP = CronExpression.EVERY_YEAR; @Injectable() export class MeteringSchedulerService implements OnModuleInit { + private readonly resetGaugesByJob = new Map void>(); + constructor( private readonly schedulerRegistry: SchedulerRegistry, private readonly locksEvents: LocksEvents, @Inject(StatsDService) private readonly statsd: StatsD, + private readonly metrics: SchedulerMetrics, @Inject(Logger) private readonly logger: LoggerService ) {} onModuleInit(): void { this.locksEvents.jobSkips$.subscribe(({ key, reason }) => { this.statsd.increment('metering.scheduler.skipped', { job: key, reason }); + this.metrics.skips.inc({ job: key, reason }); + if (reason === 'ownership-unavailable') { + this.resetGaugesByJob.get(key)?.(); + } }); this.locksEvents.events$.subscribe((event) => { if (event.type !== 'lock-lost') { @@ -43,6 +51,10 @@ export class MeteringSchedulerService implements OnModuleInit { key: event.key, detectedBy: event.detectedBy, }); + this.metrics.lockLost.inc({ + key: event.key, + detected_by: event.detectedBy, + }); this.logger.warn( `Lock lost: ${event.key} (${event.detectedBy})`, 'MeteringScheduler' @@ -50,7 +62,15 @@ export class MeteringSchedulerService implements OnModuleInit { }); } - schedule(job: SchedulerJob, cron: string): void { + /** + * Starts `job` on `cron`. `resetGauges` runs whenever another instance owns + * the job, so this instance stops serving the job's last gauge values. + */ + schedule(job: SchedulerJob, cron: string, resetGauges?: () => void): void { + this.metrics.initializeJob(job); + if (resetGauges) { + this.resetGaugesByJob.set(job, resetGauges); + } const cronJob = this.schedulerRegistry.getCronJob(job); cronJob.setTime(new CronTime(cron)); cronJob.start(); @@ -64,11 +84,13 @@ export class MeteringSchedulerService implements OnModuleInit { try { const outcome = await fn(); this.statsd.increment('metering.scheduler.run', { job, outcome }); + this.metrics.runs.inc({ job, outcome }); } catch (err) { this.statsd.increment('metering.scheduler.run', { job, outcome: 'error', }); + this.metrics.runs.inc({ job, outcome: 'error' }); throw err; } } diff --git a/libs/metering/src/lib/metering-sweep-scheduler.service.spec.ts b/libs/metering/src/lib/metering-sweep-scheduler.service.spec.ts index ac49dd9..e91382d 100644 --- a/libs/metering/src/lib/metering-sweep-scheduler.service.spec.ts +++ b/libs/metering/src/lib/metering-sweep-scheduler.service.spec.ts @@ -8,18 +8,24 @@ import { InMemoryLockStore, LocksModule, LocksStorage } from '@nestjs/locks'; import { ScheduleModule, SchedulerRegistry } from '@nestjs/schedule'; import { Test, type TestingModule } from '@nestjs/testing'; import * as Sentry from '@sentry/nestjs'; +import { Registry } from '@prometheus-io/client'; import { StatsDService, type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; import { MeteringSweepSchedulerConfig } from './metering-scheduler.config'; import { MeteringSchedulerService } from './metering-scheduler.service'; import { MeteringSweepSchedulerService } from './metering-sweep-scheduler.service'; import { MeteringSweepService } from './metering-sweep.service'; +import { SchedulerMetrics } from './metering-scheduler.metrics'; +import { SweepMetrics } from './metering-sweep.metrics'; +import { RefillMetrics } from './usage-refill.metrics'; import { UsageRefillService } from './usage-refill.service'; import type { SweepAllResult } from './metering.types'; +import { metricValues } from '../testing'; jest.mock('@nestjs/schedule', () => jest @@ -59,6 +65,10 @@ describe('MeteringSweepSchedulerService', () => { { provide: MeteringSweepService, useValue: sweepService }, { provide: UsageRefillService, useValue: refillService }, { provide: StatsDService, useValue: statsd }, + { provide: PrometheusRegistry, useValue: new Registry() }, + RefillMetrics, + SchedulerMetrics, + SweepMetrics, { provide: Logger, useValue: logger }, ], }).compile(); @@ -248,6 +258,32 @@ describe('MeteringSweepSchedulerService', () => { { job: 'sweep', reason: 'ownership-unavailable' } ); }); + + it('clears the watermark age gauge', async () => { + moduleRef.get(SweepMetrics).watermarkAge.set({ slug: 'tokens' }, 60); + + await service.sweep(); + + expect( + await metricValues( + moduleRef.get(PrometheusRegistry), + 'metering_sweep_watermark_age_seconds' + ) + ).toEqual([]); + }); + + it('zeroes the refill gauges', async () => { + moduleRef.get(RefillMetrics).counters.set(12); + + await service.sweep(); + + expect( + await metricValues( + moduleRef.get(PrometheusRegistry), + 'metering_refill_counters' + ) + ).toEqual([{ value: 0, labels: {} }]); + }); }); describe('when a sweep is still running on another instance', () => { @@ -269,6 +305,19 @@ describe('MeteringSweepSchedulerService', () => { { job: 'sweep', reason: 'run-lock-unavailable' } ); }); + + it('keeps the watermark age gauge', async () => { + moduleRef.get(SweepMetrics).watermarkAge.set({ slug: 'tokens' }, 60); + + await service.sweep(); + + expect( + await metricValues( + moduleRef.get(PrometheusRegistry), + 'metering_sweep_watermark_age_seconds' + ) + ).toEqual([{ value: 60, labels: { slug: 'tokens' } }]); + }); }); describe('when the lock store fails', () => { diff --git a/libs/metering/src/lib/metering-sweep-scheduler.service.ts b/libs/metering/src/lib/metering-sweep-scheduler.service.ts index 1fd00b3..01d3a08 100644 --- a/libs/metering/src/lib/metering-sweep-scheduler.service.ts +++ b/libs/metering/src/lib/metering-sweep-scheduler.service.ts @@ -19,6 +19,8 @@ import { SCHEDULED_AT_BOOTSTRAP, } from './metering-scheduler.service'; import { MeteringSweepService } from './metering-sweep.service'; +import { SweepMetrics } from './metering-sweep.metrics'; +import { RefillMetrics } from './usage-refill.metrics'; import { UsageRefillService } from './usage-refill.service'; @Injectable() @@ -28,13 +30,19 @@ export class MeteringSweepSchedulerService implements OnApplicationBootstrap { private readonly meteringSchedulerService: MeteringSchedulerService, private readonly meteringSweepService: MeteringSweepService, private readonly usageRefillService: UsageRefillService, + private readonly sweepMetrics: SweepMetrics, + private readonly refillMetrics: RefillMetrics, @Inject(Logger) private readonly logger: LoggerService ) {} onApplicationBootstrap(): void { this.meteringSchedulerService.schedule( 'sweep', - this.meteringSweepSchedulerConfig.cron + this.meteringSweepSchedulerConfig.cron, + () => { + this.sweepMetrics.resetGauges(); + this.refillMetrics.resetGauges(); + } ); } diff --git a/libs/metering/src/lib/metering-sweep.metrics.ts b/libs/metering/src/lib/metering-sweep.metrics.ts new file mode 100644 index 0000000..13f6ee4 --- /dev/null +++ b/libs/metering/src/lib/metering-sweep.metrics.ts @@ -0,0 +1,86 @@ +/* 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 } from '@nestjs/common'; +import type { Registry } from '@prometheus-io/client'; + +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; + +import { counter, gauge, jobHistogram } from './utils/metrics'; + +@Injectable() +export class SweepMetrics { + readonly sweeps; + readonly duration; + readonly allDuration; + readonly watermarkAge; + readonly watermarkHeld; + readonly sessionsOpened; + readonly sessionsCorrected; + readonly dispatched; + readonly subjectErrors; + readonly dispatchErrors; + + constructor(@Inject(PrometheusRegistry) registry: Registry) { + this.sweeps = counter(registry, 'metering_sweep_total', 'Meter sweeps', [ + 'outcome', + 'slug', + ]); + this.duration = jobHistogram( + registry, + 'metering_sweep_duration_seconds', + 'Duration of one meter sweep', + ['slug'] + ); + this.allDuration = jobHistogram( + registry, + 'metering_sweep_all_duration_seconds', + 'Duration of a sweep over every meter' + ); + this.watermarkAge = gauge( + registry, + 'metering_sweep_watermark_age_seconds', + 'Age of the sweep watermark when a meter sweep starts', + ['slug'] + ); + this.watermarkHeld = counter( + registry, + 'metering_sweep_watermark_held_total', + 'Meter sweeps that held the watermark back', + ['slug'] + ); + this.sessionsOpened = counter( + registry, + 'metering_sweep_sessions_opened_total', + 'Sessions opened by the sweep', + ['slug'] + ); + this.sessionsCorrected = counter( + registry, + 'metering_sweep_sessions_corrected_total', + 'Counted sessions corrected by the sweep', + ['slug'] + ); + this.dispatched = counter( + registry, + 'metering_sweep_dispatched_total', + 'Threshold notifications dispatched and recorded', + ['client_id', 'slug', 'threshold'] + ); + this.subjectErrors = counter( + registry, + 'metering_sweep_subject_errors_total', + 'Subjects the sweep failed to process' + ); + this.dispatchErrors = counter( + registry, + 'metering_sweep_dispatch_errors_total', + 'Threshold notifications that failed to dispatch' + ); + } + + resetGauges(): void { + this.watermarkAge.reset(); + } +} diff --git a/libs/metering/src/lib/metering-sweep.service.spec.ts b/libs/metering/src/lib/metering-sweep.service.spec.ts index d3f0225..11761c7 100644 --- a/libs/metering/src/lib/metering-sweep.service.spec.ts +++ b/libs/metering/src/lib/metering-sweep.service.spec.ts @@ -5,6 +5,7 @@ import { Logger } from '@nestjs/common'; import type { LoggerService } from '@nestjs/common'; import { Test } from '@nestjs/testing'; +import { Registry } from '@prometheus-io/client'; import { MeterBySlugResultUtil, @@ -17,6 +18,7 @@ import { StatsDService, type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; import { MockMeteringSweepConfig, @@ -24,11 +26,13 @@ import { } from './metering-sweep.config'; import { CATCH_UP_SLICE_MS } from './metering.constants'; import { MeteringSweepManager } from './metering-sweep.manager'; +import { SweepMetrics } from './metering-sweep.metrics'; import { notificationKey } from './utils/notificationKey'; import { MeteringSweepService } from './metering-sweep.service'; import { MeteringWebhookManager } from './metering-webhook.manager'; import { UsageCountersManager } from './usage-counters.manager'; import { UsageGrantsManager } from './usage-grants.manager'; +import { metricValues } from '../testing'; const CLIENT_ID = 'vpn'; const SLUG = 'tokens'; @@ -66,6 +70,7 @@ describe('MeteringSweepService', () => { Pick >; let statsd: jest.Mocked>; + let registry: Registry; let logger: jest.Mocked>; function utilFor(raw: StrapiMeterRaw): MeterBySlugResultUtil { @@ -114,6 +119,7 @@ describe('MeteringSweepService', () => { usageGrantsManager = { getActiveGrantedAmount: jest.fn().mockResolvedValue(0), }; + registry = new Registry(); statsd = { increment: jest.fn(), timing: jest.fn(), gauge: jest.fn() }; logger = { error: jest.fn(), log: jest.fn(), warn: jest.fn() }; @@ -130,6 +136,8 @@ describe('MeteringSweepService', () => { { provide: UsageGrantsManager, useValue: usageGrantsManager }, { provide: UsageCountersManager, useValue: usageCountersManager }, { provide: StatsDService, useValue: statsd }, + { provide: PrometheusRegistry, useValue: registry }, + SweepMetrics, { provide: Logger, useValue: logger }, ], }).compile(); @@ -212,6 +220,19 @@ describe('MeteringSweepService', () => { ); }); + it('sets the watermark age in seconds in Prometheus', async () => { + await service.sweep(params, NOW); + + expect( + await metricValues(registry, 'metering_sweep_watermark_age_seconds') + ).toEqual([ + { + value: (NOW.getTime() - WATERMARK.getTime()) / 1000, + labels: { slug: SLUG }, + }, + ]); + }); + describe('catching up a stale watermark', () => { const SLICE_MS = CATCH_UP_SLICE_MS; const LAG_MS = MockMeteringSweepConfig.watermarkLagMs; @@ -548,6 +569,19 @@ describe('MeteringSweepService', () => { ); }); + it('records a delivered webhook by client, slug and threshold in Prometheus', async () => { + await service.sweep(params, NOW); + + expect( + await metricValues(registry, 'metering_sweep_dispatched_total') + ).toEqual([ + { + value: 1, + labels: { client_id: CLIENT_ID, slug: SLUG, threshold: '80' }, + }, + ]); + }); + it('counts each webhook that receives the crossing', async () => { meteringConfigurationManager.getMeterResultUtil.mockResolvedValue( utilFor( @@ -577,6 +611,30 @@ describe('MeteringSweepService', () => { ]); }); + it('records each webhook that receives the crossing in Prometheus', async () => { + meteringConfigurationManager.getMeterResultUtil.mockResolvedValue( + utilFor( + meter({ + webhooks: [ + StrapiMeterWebhookFactory({ signingClientId: 'wh-a' }), + StrapiMeterWebhookFactory({ signingClientId: 'wh-b' }), + ], + }) + ) + ); + + await service.sweep(params, NOW); + + expect( + await metricValues(registry, 'metering_sweep_dispatched_total') + ).toEqual([ + { + value: 2, + labels: { client_id: CLIENT_ID, slug: SLUG, threshold: '80' }, + }, + ]); + }); + it('does not count a webhook whose delivery failed', async () => { meteringWebhookManager.dispatch.mockRejectedValue(new Error('502')); @@ -588,6 +646,26 @@ describe('MeteringSweepService', () => { ); }); + it('records no delivery in Prometheus for a webhook whose delivery failed', async () => { + meteringWebhookManager.dispatch.mockRejectedValue(new Error('502')); + + await service.sweep(params, NOW); + + expect( + await metricValues(registry, 'metering_sweep_dispatched_total') + ).toEqual([]); + }); + + it('records the failed delivery in Prometheus', async () => { + meteringWebhookManager.dispatch.mockRejectedValue(new Error('502')); + + await service.sweep(params, NOW); + + expect( + await metricValues(registry, 'metering_sweep_dispatch_errors_total') + ).toEqual([{ value: 1, labels: {} }]); + }); + it('does not count a delivered webhook whose notification failed to save', async () => { meteringSweepManager.recordNotifications.mockRejectedValue( new Error('clickhouse') @@ -601,6 +679,18 @@ describe('MeteringSweepService', () => { ); }); + it('records no delivery in Prometheus when the notification failed to save', async () => { + meteringSweepManager.recordNotifications.mockRejectedValue( + new Error('clickhouse') + ); + + await service.sweep(params, NOW).catch(() => undefined); + + expect( + await metricValues(registry, 'metering_sweep_dispatched_total') + ).toEqual([]); + }); + it('records nothing when the only webhook fails, so the next sweep retries', async () => { meteringWebhookManager.dispatch.mockRejectedValue(new Error('502')); @@ -623,6 +713,16 @@ describe('MeteringSweepService', () => { ); }); + it('records the held watermark in Prometheus', async () => { + meteringWebhookManager.dispatch.mockRejectedValue(new Error('502')); + + await service.sweep(params, NOW); + + expect( + await metricValues(registry, 'metering_sweep_watermark_held_total') + ).toEqual([{ value: 1, labels: { slug: SLUG } }]); + }); + it('holds the watermark when another webhook still succeeds', async () => { meteringConfigurationManager.getMeterResultUtil.mockResolvedValue( utilFor( @@ -684,6 +784,27 @@ describe('MeteringSweepService', () => { expect(logger.error).toHaveBeenCalled(); expect(meteringSweepManager.advanceWatermark).not.toHaveBeenCalled(); }); + + it('records a subject that throws in Prometheus', async () => { + meteringSweepManager.findWindowCandidates.mockResolvedValue([ + { subject: 'user-1', usage: 90 }, + { subject: 'user-2', usage: 90 }, + ]); + usageGrantsManager.getActiveGrantedAmount.mockImplementation( + async (subject) => { + if (subject === 'user-1') { + throw new Error('firestore'); + } + return 0; + } + ); + + await service.sweep(params, NOW); + + expect( + await metricValues(registry, 'metering_sweep_subject_errors_total') + ).toEqual([{ value: 1, labels: {} }]); + }); }); describe('observability', () => { @@ -713,6 +834,62 @@ describe('MeteringSweepService', () => { { slug: SLUG } ); }); + + it('records the outcome by slug in Prometheus', async () => { + await service.sweep(params, NOW); + + expect(await metricValues(registry, 'metering_sweep_total')).toEqual([ + { value: 1, labels: { outcome: 'no-candidates', slug: SLUG } }, + ]); + }); + + it('records an error outcome in Prometheus when the sweep fails', async () => { + meteringSweepManager.findWindowCandidates.mockRejectedValue( + new Error('clickhouse') + ); + + await service.sweep(params, NOW).catch(() => undefined); + + expect(await metricValues(registry, 'metering_sweep_total')).toEqual([ + { value: 1, labels: { outcome: 'error', slug: SLUG } }, + ]); + }); + + it('times a failed sweep by slug in Prometheus', async () => { + meteringSweepManager.findWindowCandidates.mockRejectedValue( + new Error('clickhouse') + ); + + await service.sweep(params, NOW).catch(() => undefined); + + expect( + (await metricValues(registry, 'metering_sweep_duration_seconds')).find( + ({ metricName }) => + metricName === 'metering_sweep_duration_seconds_count' + ) + ).toEqual({ + metricName: 'metering_sweep_duration_seconds_count', + value: 1, + labels: { slug: SLUG }, + }); + }); + + it('times a sweep over every meter in Prometheus', async () => { + await service.sweepAll(NOW); + + expect( + ( + await metricValues(registry, 'metering_sweep_all_duration_seconds') + ).find( + ({ metricName }) => + metricName === 'metering_sweep_all_duration_seconds_count' + ) + ).toEqual({ + metricName: 'metering_sweep_all_duration_seconds_count', + value: 1, + labels: {}, + }); + }); }); describe('session start detection', () => { @@ -885,6 +1062,32 @@ describe('MeteringSweepService', () => { ); }); + it('records the opened session in Prometheus', async () => { + await service.sweep(params, NOW); + + expect( + await metricValues(registry, 'metering_sweep_sessions_opened_total') + ).toEqual([{ value: 1, labels: { slug: SLUG } }]); + }); + + it('records the corrected session in Prometheus', async () => { + usageCountersManager.findSessionStarts.mockResolvedValue( + new Map([['user-1', new Date(startedAt.getTime() + 60_000)]]) + ); + meteringSweepManager.findSessionUsage.mockResolvedValue([ + { subject: 'user-1', sessionStart: startedAt, usage: 9 }, + ]); + + await service.sweep(params, NOW); + + expect( + await metricValues( + registry, + 'metering_sweep_sessions_corrected_total' + ) + ).toEqual([{ value: 1, labels: { slug: SLUG } }]); + }); + it('writes a session Redis has not counted at all', async () => { meteringSweepManager.findSessionUsage.mockResolvedValue([ { subject: 'user-1', sessionStart: startedAt, usage: 9 }, diff --git a/libs/metering/src/lib/metering-sweep.service.ts b/libs/metering/src/lib/metering-sweep.service.ts index a6aff4e..d1f04d9 100644 --- a/libs/metering/src/lib/metering-sweep.service.ts +++ b/libs/metering/src/lib/metering-sweep.service.ts @@ -15,6 +15,7 @@ import { type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { SweepMetrics } from './metering-sweep.metrics'; import { CATCH_UP_SLICE_MS, MAX_TIMESTAMP_FUTURE_MS, @@ -83,6 +84,7 @@ export class MeteringSweepService { private readonly usageGrantsManager: UsageGrantsManager, private readonly usageCountersManager: UsageCountersManager, @Inject(StatsDService) private readonly statsd: StatsD, + private readonly metrics: SweepMetrics, @Inject(Logger) private readonly logger: LoggerService ) {} @@ -117,6 +119,7 @@ export class MeteringSweepService { } this.statsd.timing('metering.sweep_all.duration', Date.now() - startedAt); + this.metrics.allDuration.observe((Date.now() - startedAt) / 1000); return { total: meters.length, held, failed }; } @@ -147,6 +150,11 @@ export class MeteringSweepService { this.statsd.timing('metering.sweep.duration', Date.now() - startedAt, { slug: params.slug, }); + this.metrics.sweeps.inc({ outcome, slug: params.slug }); + this.metrics.duration.observe( + { slug: params.slug }, + (Date.now() - startedAt) / 1000 + ); } } @@ -172,6 +180,10 @@ export class MeteringSweepService { now.getTime() - watermark.getTime(), { slug: params.slug } ); + this.metrics.watermarkAge.set( + { slug: params.slug }, + (now.getTime() - watermark.getTime()) / 1000 + ); const thresholds = meterResult .getNotificationThresholds() @@ -343,6 +355,7 @@ export class MeteringSweepService { this.statsd.increment('metering.sweep.watermark_held', { slug: params.slug, }); + this.metrics.watermarkHeld.inc({ slug: params.slug }); return { ...totals, outcome: this.outcomeFor(totals, true), @@ -420,6 +433,7 @@ export class MeteringSweepService { } else { failed += 1; this.statsd.increment('metering.sweep.subject_error'); + this.metrics.subjectErrors.inc(); this.logger.error(result.reason); } } @@ -432,6 +446,11 @@ export class MeteringSweepService { slug: notification.slug, threshold: String(notification.threshold), }); + this.metrics.dispatched.inc({ + client_id: notification.clientId, + slug: notification.slug, + threshold: String(notification.threshold), + }); } } @@ -464,6 +483,7 @@ export class MeteringSweepService { this.statsd.increment('metering.sweep.sessions_opened', opened.length, { slug: params.slug, }); + this.metrics.sessionsOpened.inc({ slug: params.slug }, opened.length); await this.correctCountedSessions( params, meter.window.durationMs, @@ -517,6 +537,7 @@ export class MeteringSweepService { slug: params.slug, } ); + this.metrics.sessionsCorrected.inc({ slug: params.slug }, diverged.length); } private async findWindowCandidates( @@ -624,6 +645,7 @@ export class MeteringSweepService { }); } catch (err) { this.statsd.increment('metering.sweep.dispatch_error'); + this.metrics.dispatchErrors.inc(); this.logger.error(err); failed += 1; continue; diff --git a/libs/metering/src/lib/metering-webhook.manager.spec.ts b/libs/metering/src/lib/metering-webhook.manager.spec.ts index ff26d84..45e183a 100644 --- a/libs/metering/src/lib/metering-webhook.manager.spec.ts +++ b/libs/metering/src/lib/metering-webhook.manager.spec.ts @@ -5,8 +5,10 @@ import { Logger } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import { VError } from 'verror'; +import { Registry } from '@prometheus-io/client'; import { MockStatsDProvider } from '@entitlements/shared/metrics/statsd'; +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; import { MeteringWebhookManager } from './metering-webhook.manager'; import { MeteringConfig, MockMeteringConfig } from './metering.config'; @@ -15,7 +17,9 @@ import { MissingClientSecretError, WebhookDispatchError, } from './metering.error'; +import { WebhookMetrics } from './metering-webhook.metrics'; import type { WebhookDispatchParams } from './metering.types'; +import { incrementedMetricValues, metricValues } from '../testing'; describe('MeteringWebhookManager', () => { const SIGNING_CLIENT_ID = 'vpn'; @@ -28,16 +32,20 @@ describe('MeteringWebhookManager', () => { let meteringWebhookManager: MeteringWebhookManager; let logger: { error: jest.Mock; log: jest.Mock }; let fetchMock: jest.SpyInstance; + let registry: Registry; async function build( meteringConfig: MeteringConfig = METERING_CONFIG ): Promise { + registry = new Registry(); const moduleRef = await Test.createTestingModule({ providers: [ MeteringWebhookManager, { provide: MeteringConfig, useValue: meteringConfig }, { provide: Logger, useValue: logger }, MockStatsDProvider, + { provide: PrometheusRegistry, useValue: registry }, + WebhookMetrics, ], }).compile(); return moduleRef.get(MeteringWebhookManager); @@ -181,6 +189,84 @@ describe('MeteringWebhookManager', () => { ).rejects.toThrow(MissingClientSecretError); expect(fetchMock).not.toHaveBeenCalled(); }); + + describe('Prometheus metrics', () => { + it('starts dispatch errors at zero for each configured client', async () => { + expect( + await metricValues(registry, 'metering_webhook_dispatch_errors_total') + ).toEqual([ + { value: 0, labels: { signing_client_id: SIGNING_CLIENT_ID } }, + ]); + }); + + it('records a dispatch by signing client and status class', async () => { + fetchMock.mockResolvedValueOnce(new Response(null, { status: 204 })); + + await meteringWebhookManager.dispatch(params()); + + expect( + await metricValues(registry, 'metering_webhook_dispatch_total') + ).toEqual([ + { + value: 1, + labels: { signing_client_id: SIGNING_CLIENT_ID, status: '2xx' }, + }, + ]); + }); + + it('records no dispatch error for a 2xx response', async () => { + await meteringWebhookManager.dispatch(params()); + + expect( + await incrementedMetricValues( + registry, + 'metering_webhook_dispatch_errors_total' + ) + ).toEqual([]); + }); + + it('records a dispatch error for a non-2xx response', async () => { + fetchMock.mockResolvedValueOnce(new Response('', { status: 503 })); + + await meteringWebhookManager.dispatch(params()).catch(() => undefined); + + expect( + await incrementedMetricValues( + registry, + 'metering_webhook_dispatch_errors_total' + ) + ).toEqual([ + { value: 1, labels: { signing_client_id: SIGNING_CLIENT_ID } }, + ]); + }); + + it('records a dispatch error for a network failure', async () => { + fetchMock.mockRejectedValueOnce(new Error('ECONNRESET')); + + await meteringWebhookManager.dispatch(params()).catch(() => undefined); + + expect( + await incrementedMetricValues( + registry, + 'metering_webhook_dispatch_errors_total' + ) + ).toEqual([ + { value: 1, labels: { signing_client_id: SIGNING_CLIENT_ID } }, + ]); + }); + + it('records a dispatch skipped for a missing signing secret', async () => { + await meteringWebhookManager + .dispatch(params({ signingClientId: 'no-such-client' })) + .catch(() => undefined); + + expect( + await metricValues(registry, 'metering_webhook_no_secret_total') + ).toEqual([ + { value: 1, labels: { signing_client_id: 'no-such-client' } }, + ]); + }); + }); }); describe('constructor', () => { diff --git a/libs/metering/src/lib/metering-webhook.manager.ts b/libs/metering/src/lib/metering-webhook.manager.ts index ae42386..e17c2e0 100644 --- a/libs/metering/src/lib/metering-webhook.manager.ts +++ b/libs/metering/src/lib/metering-webhook.manager.ts @@ -13,6 +13,7 @@ import { type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { WebhookMetrics } from './metering-webhook.metrics'; import { MeteringConfig } from './metering.config'; import { EmptyClientSecretError, @@ -33,6 +34,7 @@ export class MeteringWebhookManager { constructor( meteringConfig: MeteringConfig, @Inject(StatsDService) private readonly statsd: StatsD, + private readonly metrics: WebhookMetrics, @Inject(Logger) private readonly logger: LoggerService ) { this.secretByClientId = new Map(); @@ -45,6 +47,7 @@ export class MeteringWebhookManager { } this.secretByClientId.set(clientId, normalizedSecret); } + this.metrics.initializeClients([...this.secretByClientId.keys()]); } /** @@ -58,6 +61,9 @@ export class MeteringWebhookManager { this.statsd.increment('metering.webhook.no_secret', { signingClientId: params.signingClientId, }); + this.metrics.noSecret.inc({ + signing_client_id: params.signingClientId, + }); throw new MissingClientSecretError(params.signingClientId, params.slug); } @@ -100,6 +106,10 @@ export class MeteringWebhookManager { signingClientId: params.signingClientId, status: statusBucket(response.status), }); + this.metrics.dispatches.inc({ + signing_client_id: params.signingClientId, + status: statusBucket(response.status), + }); if (!response.ok) { throw this.reportDispatchError( params, @@ -124,6 +134,9 @@ export class MeteringWebhookManager { this.statsd.increment('metering.webhook.dispatch_error', { signingClientId: params.signingClientId, }); + this.metrics.dispatchErrors.inc({ + signing_client_id: params.signingClientId, + }); this.logger.error(err); return err; } diff --git a/libs/metering/src/lib/metering-webhook.metrics.spec.ts b/libs/metering/src/lib/metering-webhook.metrics.spec.ts new file mode 100644 index 0000000..a99c284 --- /dev/null +++ b/libs/metering/src/lib/metering-webhook.metrics.spec.ts @@ -0,0 +1,31 @@ +/* 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 { Registry } from '@prometheus-io/client'; + +import { WebhookMetrics } from './metering-webhook.metrics'; +import { metricValues, zeroMetricValues } from '../testing'; + +describe('WebhookMetrics', () => { + let registry: Registry; + + beforeEach(() => { + registry = new Registry(); + }); + + describe('initializeClients', () => { + it('starts dispatch errors at zero for each signing client', async () => { + new WebhookMetrics(registry).initializeClients(['vpn', 'relay']); + + expect( + await metricValues(registry, 'metering_webhook_dispatch_errors_total') + ).toEqual( + zeroMetricValues([ + { signing_client_id: 'vpn' }, + { signing_client_id: 'relay' }, + ]) + ); + }); + }); +}); diff --git a/libs/metering/src/lib/metering-webhook.metrics.ts b/libs/metering/src/lib/metering-webhook.metrics.ts new file mode 100644 index 0000000..7feb5e4 --- /dev/null +++ b/libs/metering/src/lib/metering-webhook.metrics.ts @@ -0,0 +1,45 @@ +/* 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 } from '@nestjs/common'; +import type { Registry } from '@prometheus-io/client'; + +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; + +import { counter, initialize } from './utils/metrics'; + +@Injectable() +export class WebhookMetrics { + readonly dispatches; + readonly dispatchErrors; + readonly noSecret; + + constructor(@Inject(PrometheusRegistry) registry: Registry) { + this.dispatches = counter( + registry, + 'metering_webhook_dispatch_total', + 'Webhook dispatches by response status class', + ['signing_client_id', 'status'] + ); + this.dispatchErrors = counter( + registry, + 'metering_webhook_dispatch_errors_total', + 'Webhook dispatches with a non-2xx response', + ['signing_client_id'] + ); + this.noSecret = counter( + registry, + 'metering_webhook_no_secret_total', + 'Webhook dispatches skipped for a missing signing secret', + ['signing_client_id'] + ); + } + + initializeClients(signingClientIds: string[]): void { + initialize( + this.dispatchErrors, + signingClientIds.map((signing_client_id) => ({ signing_client_id })) + ); + } +} diff --git a/libs/metering/src/lib/usage-grants.manager.spec.ts b/libs/metering/src/lib/usage-grants.manager.spec.ts index e430860..c0852b4 100644 --- a/libs/metering/src/lib/usage-grants.manager.spec.ts +++ b/libs/metering/src/lib/usage-grants.manager.spec.ts @@ -5,11 +5,13 @@ import { Timestamp } from '@google-cloud/firestore'; import { Logger, type LoggerService } from '@nestjs/common'; import { Test } from '@nestjs/testing'; +import { Registry } from '@prometheus-io/client'; import { StatsDService, type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; import { UsageGrantRecordFactory } from './metering.factories'; import { @@ -19,6 +21,7 @@ import { import { MockMeteringFirestoreProvider } from './metering-firestore.provider'; import { MeteringRedisClient } from './metering-redis.provider'; import { UsageGrantsLoadError } from './metering.error'; +import { UsageGrantsMetrics } from './usage-grants.metrics'; import type { MeteringRedis } from './metering.types'; import { UsageGrantsManager } from './usage-grants.manager'; import { @@ -26,6 +29,7 @@ import { getUsageGrants, insertUsageGrant, } from './usage-grants.repository'; +import { incrementedMetricValues } from '../testing'; jest.mock('./usage-grants.repository'); @@ -40,11 +44,13 @@ describe('UsageGrantsManager', () => { let cache: Map; let redis: jest.Mocked>; let statsd: jest.Mocked>; + let registry: Registry; let logger: jest.Mocked>; const now = new Date('2026-05-15T12:00:00.000Z'); beforeEach(async () => { jest.clearAllMocks(); + registry = new Registry(); cache = new Map(); redis = { get: jest.fn((key: string) => Promise.resolve(cache.get(key) ?? null)), @@ -69,6 +75,8 @@ describe('UsageGrantsManager', () => { MockMeteringFirestoreProvider, { provide: MeteringRedisClient, useValue: redis }, { provide: StatsDService, useValue: statsd }, + { provide: PrometheusRegistry, useValue: registry }, + UsageGrantsMetrics, { provide: Logger, useValue: logger }, ], }).compile(); @@ -143,6 +151,25 @@ describe('UsageGrantsManager', () => { ); }); + it('records a cache clear failure in Prometheus', async () => { + redis.del.mockRejectedValueOnce(new Error('connection closed')); + + await manager.createGrant({ + subject: 'user-1', + slug: 'tokens', + amount: 500, + grantedBy: 'rp-1', + expiresAt: null, + }); + + expect( + await incrementedMetricValues( + registry, + 'metering_usage_grants_cache_errors_total' + ) + ).toEqual([{ value: 1, labels: { operation: 'clear' } }]); + }); + it('propagates a repository failure', async () => { jest .mocked(insertUsageGrant) @@ -342,6 +369,24 @@ describe('UsageGrantsManager', () => { ); }); + it('records a cache read failure in Prometheus', async () => { + redis.get.mockRejectedValueOnce(new Error('connection closed')); + jest + .mocked(getUsageGrants) + .mockResolvedValue([ + UsageGrantRecordFactory({ slug: 'tokens', amount: 100 }), + ]); + + await manager.getActiveGrantedAmount('user-1', 'tokens', now); + + expect( + await incrementedMetricValues( + registry, + 'metering_usage_grants_cache_errors_total' + ) + ).toEqual([{ value: 1, labels: { operation: 'read' } }]); + }); + it('reads Firestore when the cached value has an unexpected shape', async () => { cache.set(CACHE_KEY, '[{"slug":"tokens"}]'); jest @@ -372,6 +417,25 @@ describe('UsageGrantsManager', () => { ); }); + it('records a cache write failure in Prometheus', async () => { + redis.set.mockRejectedValueOnce(new Error('OOM')); + jest + .mocked(getUsageGrants) + .mockResolvedValue([ + UsageGrantRecordFactory({ slug: 'tokens', amount: 100 }), + ]); + + await manager.getActiveGrantedAmount('user-1', 'tokens', now); + await settle(); + + expect( + await incrementedMetricValues( + registry, + 'metering_usage_grants_cache_errors_total' + ) + ).toEqual([{ value: 1, labels: { operation: 'write' } }]); + }); + it('wraps a repository failure in UsageGrantsLoadError', async () => { jest .mocked(getUsageGrants) @@ -407,5 +471,22 @@ describe('UsageGrantsManager', () => { 'metering.usage_grants.cache_read_error' ); }); + + it('does not record a repository failure as a cache error in Prometheus', async () => { + jest + .mocked(getUsageGrants) + .mockRejectedValue(new Error('firestore down')); + + await manager + .getActiveGrantedAmount('user-1', 'tokens', now) + .catch(() => undefined); + + expect( + await incrementedMetricValues( + registry, + 'metering_usage_grants_cache_errors_total' + ) + ).toEqual([]); + }); }); }); diff --git a/libs/metering/src/lib/usage-grants.manager.ts b/libs/metering/src/lib/usage-grants.manager.ts index 2bec302..8ad7337 100644 --- a/libs/metering/src/lib/usage-grants.manager.ts +++ b/libs/metering/src/lib/usage-grants.manager.ts @@ -20,6 +20,7 @@ import { type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { UsageGrantsMetrics } from './usage-grants.metrics'; import { MeteringConfig } from './metering.config'; import { MeteringFirestore } from './metering-firestore.provider'; import { MeteringRedisClient } from './metering-redis.provider'; @@ -74,11 +75,15 @@ export class UsageGrantsManager { @Inject(MeteringFirestore) private readonly firestore: Firestore, @Inject(MeteringRedisClient) redis: MeteringRedis, @Inject(StatsDService) private readonly statsd: StatsD, + private readonly metrics: UsageGrantsMetrics, @Inject(Logger) private readonly logger: LoggerService ) { this.grantsCache = new RedisAdapter(redis); this.grantsCacheStrategy = new CacheFirstStrategy( - () => this.statsd.increment('metering.usage_grants.cache_write_error'), + () => { + this.statsd.increment('metering.usage_grants.cache_write_error'); + this.metrics.cacheErrors.inc({ operation: 'write' }); + }, undefined, this.logger ); @@ -162,6 +167,7 @@ export class UsageGrantsManager { throw err; } this.statsd.increment('metering.usage_grants.cache_read_error'); + this.metrics.cacheErrors.inc({ operation: 'read' }); this.logger.error(err); return this.loadSubjectGrants(subject); } @@ -179,6 +185,7 @@ export class UsageGrantsManager { await this.grantsCache.del(usageGrantsCacheKey(subject)); } catch (err) { this.statsd.increment('metering.usage_grants.cache_clear_error'); + this.metrics.cacheErrors.inc({ operation: 'clear' }); this.logger.error(err); } } diff --git a/libs/metering/src/lib/usage-grants.metrics.spec.ts b/libs/metering/src/lib/usage-grants.metrics.spec.ts new file mode 100644 index 0000000..9c19bdb --- /dev/null +++ b/libs/metering/src/lib/usage-grants.metrics.spec.ts @@ -0,0 +1,30 @@ +/* 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 { Registry } from '@prometheus-io/client'; + +import { UsageGrantsMetrics } from './usage-grants.metrics'; +import { metricValues, zeroMetricValues } from '../testing'; + +describe('UsageGrantsMetrics', () => { + let registry: Registry; + + beforeEach(() => { + registry = new Registry(); + }); + + it('starts each usage grant cache operation at zero', async () => { + new UsageGrantsMetrics(registry); + + expect( + await metricValues(registry, 'metering_usage_grants_cache_errors_total') + ).toEqual( + zeroMetricValues([ + { operation: 'read' }, + { operation: 'write' }, + { operation: 'clear' }, + ]) + ); + }); +}); diff --git a/libs/metering/src/lib/usage-grants.metrics.ts b/libs/metering/src/lib/usage-grants.metrics.ts new file mode 100644 index 0000000..f8e3fff --- /dev/null +++ b/libs/metering/src/lib/usage-grants.metrics.ts @@ -0,0 +1,34 @@ +/* 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 } from '@nestjs/common'; +import type { Registry } from '@prometheus-io/client'; + +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; + +import { allOf, counter, initialize } from './utils/metrics'; + +export type UsageGrantsCacheOperation = 'read' | 'write' | 'clear'; + +@Injectable() +export class UsageGrantsMetrics { + readonly cacheErrors; + + constructor(@Inject(PrometheusRegistry) registry: Registry) { + this.cacheErrors = counter( + registry, + 'metering_usage_grants_cache_errors_total', + 'Usage grant cache failures', + ['operation'] + ); + initialize( + this.cacheErrors, + allOf({ + read: true, + write: true, + clear: true, + }).map((operation) => ({ operation })) + ); + } +} diff --git a/libs/metering/src/lib/usage-refill.metrics.spec.ts b/libs/metering/src/lib/usage-refill.metrics.spec.ts new file mode 100644 index 0000000..5518753 --- /dev/null +++ b/libs/metering/src/lib/usage-refill.metrics.spec.ts @@ -0,0 +1,29 @@ +/* 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 { Registry } from '@prometheus-io/client'; + +import { RefillMetrics } from './usage-refill.metrics'; +import { metricValues, zeroMetricValues } from '../testing'; + +describe('RefillMetrics', () => { + let registry: Registry; + + beforeEach(() => { + registry = new Registry(); + }); + + it('starts each refill outcome at zero', async () => { + new RefillMetrics(registry); + + expect(await metricValues(registry, 'metering_refill_total')).toEqual( + zeroMetricValues([ + { outcome: 'refilled' }, + { outcome: 'repaired' }, + { outcome: 'meters-rebuilt' }, + { outcome: 'checked' }, + ]) + ); + }); +}); diff --git a/libs/metering/src/lib/usage-refill.metrics.ts b/libs/metering/src/lib/usage-refill.metrics.ts new file mode 100644 index 0000000..534cb91 --- /dev/null +++ b/libs/metering/src/lib/usage-refill.metrics.ts @@ -0,0 +1,78 @@ +/* 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 } from '@nestjs/common'; +import type { Registry } from '@prometheus-io/client'; + +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; + +import type { UsageRefillOutcome } from './usage-refill.service'; +import { + allOf, + counter, + gauge, + initialize, + jobHistogram, +} from './utils/metrics'; + +@Injectable() +export class RefillMetrics { + readonly refills; + readonly duration; + readonly meterErrors; + readonly counters; + readonly sessions; + readonly dedupeKeys; + + constructor(@Inject(PrometheusRegistry) registry: Registry) { + this.refills = counter( + registry, + 'metering_refill_total', + 'Usage counter refills', + ['outcome'] + ); + initialize( + this.refills, + allOf({ + refilled: true, + repaired: true, + 'meters-rebuilt': true, + checked: true, + }).map((outcome) => ({ outcome })) + ); + this.duration = jobHistogram( + registry, + 'metering_refill_duration_seconds', + 'Duration of a usage counter refill', + ['outcome'] + ); + this.meterErrors = counter( + registry, + 'metering_refill_meter_errors_total', + 'Meters the refill failed to load', + ['slug'] + ); + this.counters = gauge( + registry, + 'metering_refill_counters', + 'Usage counters written by the last refill' + ); + this.sessions = gauge( + registry, + 'metering_refill_sessions', + 'Sessions written by the last refill' + ); + this.dedupeKeys = gauge( + registry, + 'metering_refill_dedupe_keys', + 'Dedupe keys written by the last refill' + ); + } + + resetGauges(): void { + this.counters.reset(); + this.sessions.reset(); + this.dedupeKeys.reset(); + } +} diff --git a/libs/metering/src/lib/usage-refill.service.in.spec.ts b/libs/metering/src/lib/usage-refill.service.in.spec.ts index 37bf159..83b3e21 100644 --- a/libs/metering/src/lib/usage-refill.service.in.spec.ts +++ b/libs/metering/src/lib/usage-refill.service.in.spec.ts @@ -5,6 +5,7 @@ import { Logger } from '@nestjs/common'; import { Test } from '@nestjs/testing'; import Redis from 'ioredis'; +import { Registry } from '@prometheus-io/client'; import { MeteringConfigurationManager, @@ -12,6 +13,7 @@ import { type MeteringWindow, } from '@entitlements/shared/cms'; import { StatsDService } from '@entitlements/shared/metrics/statsd'; +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; import { integrationClickHouseClient, @@ -35,6 +37,7 @@ import { MeteringUsageCountersConfig, MockMeteringUsageCountersConfig, } from './metering-usage-counters.config'; +import { RefillMetrics } from './usage-refill.metrics'; import { UsageCountersManager } from './usage-counters.manager'; import { UsageRefillManager } from './usage-refill.manager'; import { UsageRefillRepository } from './usage-refill.repository'; @@ -159,6 +162,8 @@ describeIntegration( gauge: jest.fn(), }, }, + { provide: PrometheusRegistry, useValue: new Registry() }, + RefillMetrics, { provide: Logger, useValue: { log: jest.fn(), warn: jest.fn(), error: jest.fn() }, diff --git a/libs/metering/src/lib/usage-refill.service.spec.ts b/libs/metering/src/lib/usage-refill.service.spec.ts index 875a5ca..b2ef49f 100644 --- a/libs/metering/src/lib/usage-refill.service.spec.ts +++ b/libs/metering/src/lib/usage-refill.service.spec.ts @@ -4,6 +4,7 @@ import { Logger, type LoggerService } from '@nestjs/common'; import { Test } from '@nestjs/testing'; +import { Registry } from '@prometheus-io/client'; import { MeteringConfigurationManager, @@ -14,6 +15,7 @@ import { StatsDService, type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; import { MeteringRedisConfig, @@ -29,12 +31,14 @@ import { MockMeteringUsageCountersConfig, } from './metering-usage-counters.config'; import { ClickHouseError } from './metering.error'; +import { RefillMetrics } from './usage-refill.metrics'; import { UsageCountersManager, type PopulationState, } from './usage-counters.manager'; import { UsageRefillManager } from './usage-refill.manager'; import { UsageRefillService } from './usage-refill.service'; +import { incrementedMetricValues, metricValues } from '../testing'; jest.mock('@sentry/nestjs', () => ({ captureException: jest.fn(), @@ -81,9 +85,11 @@ describe('UsageRefillService', () => { Pick >; let statsd: jest.Mocked>; + let registry: Registry; let logger: jest.Mocked>; beforeEach(async () => { + registry = new Registry(); meteringConfigurationManager = { getMeterBySlug: jest .fn() @@ -132,6 +138,8 @@ describe('UsageRefillService', () => { { provide: UsageCountersManager, useValue: countersManager }, { provide: UsageRefillManager, useValue: refillManager }, { provide: StatsDService, useValue: statsd }, + { provide: PrometheusRegistry, useValue: registry }, + RefillMetrics, { provide: Logger, useValue: logger }, ], }).compile(); @@ -155,6 +163,29 @@ describe('UsageRefillService', () => { outcome: 'checked', }); }); + + it('records the outcome in Prometheus', async () => { + await service.refillIfNeeded(NOW); + + expect( + await incrementedMetricValues(registry, 'metering_refill_total') + ).toEqual([{ value: 1, labels: { outcome: 'checked' } }]); + }); + + it('times the refill by outcome in Prometheus', async () => { + await service.refillIfNeeded(NOW); + + expect( + (await metricValues(registry, 'metering_refill_duration_seconds')).find( + ({ metricName }) => + metricName === 'metering_refill_duration_seconds_count' + ) + ).toEqual({ + metricName: 'metering_refill_duration_seconds_count', + value: 1, + labels: { outcome: 'checked' }, + }); + }); }); describe('when Redis is not fully populated', () => { @@ -176,6 +207,18 @@ describe('UsageRefillService', () => { ); }); + it.each([ + { name: 'metering_refill_counters', value: 3 }, + { name: 'metering_refill_sessions', value: 0 }, + { name: 'metering_refill_dedupe_keys', value: 4 }, + ])('sets $name to $value in Prometheus', async ({ name, value }) => { + await service.refillIfNeeded(NOW); + + expect(await metricValues(registry, name)).toEqual([ + { value, labels: {} }, + ]); + }); + it('rebuilds the dedupe keys of the whole dedupe TTL', async () => { await service.refillIfNeeded(NOW); @@ -364,6 +407,14 @@ describe('UsageRefillService', () => { ); }); + it('records the failure for that meter in Prometheus', async () => { + await service.refillIfNeeded(NOW); + + expect( + await metricValues(registry, 'metering_refill_meter_errors_total') + ).toEqual([{ value: 1, labels: { slug: 'broken' } }]); + }); + describe('while Redis is not fully populated', () => { beforeEach(() => { countersManager.findPopulationState.mockResolvedValue({ diff --git a/libs/metering/src/lib/usage-refill.service.ts b/libs/metering/src/lib/usage-refill.service.ts index 4dad1c5..5c7e064 100644 --- a/libs/metering/src/lib/usage-refill.service.ts +++ b/libs/metering/src/lib/usage-refill.service.ts @@ -13,6 +13,7 @@ import { type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { RefillMetrics } from './usage-refill.metrics'; import { MeteringRedisConfig } from './metering-redis.config'; import { MeteringSweepConfig } from './metering-sweep.config'; import { MeteringSweepManager } from './metering-sweep.manager'; @@ -51,6 +52,7 @@ export class UsageRefillService { private readonly usageCountersManager: UsageCountersManager, private readonly usageRefillManager: UsageRefillManager, @Inject(StatsDService) private readonly statsd: StatsD, + private readonly metrics: RefillMetrics, @Inject(Logger) private readonly logger: LoggerService ) {} @@ -61,6 +63,8 @@ export class UsageRefillService { this.statsd.timing('metering.refill.duration', Date.now() - startedAt, { outcome, }); + this.metrics.refills.inc({ outcome }); + this.metrics.duration.observe({ outcome }, (Date.now() - startedAt) / 1000); return outcome; } @@ -173,6 +177,7 @@ export class UsageRefillService { this.statsd.increment('metering.refill.meter_error', { slug: meterKey.slug, }); + this.metrics.meterErrors.inc({ slug: meterKey.slug }); Sentry.withScope((scope) => { scope.setTag('clientId', meterKey.clientId); scope.setTag('slug', meterKey.slug); @@ -241,6 +246,9 @@ export class UsageRefillService { this.statsd.gauge('metering.refill.counters', totals.counters); this.statsd.gauge('metering.refill.sessions', totals.sessions); this.statsd.gauge('metering.refill.dedupe_keys', totals.dedupeKeys); + this.metrics.counters.set(totals.counters); + this.metrics.sessions.set(totals.sessions); + this.metrics.dedupeKeys.set(totals.dedupeKeys); this.logger.log( `Refilled ${totals.counters} counters, ${totals.sessions} sessions and ${totals.dedupeKeys} dedupe keys for ${meters.length} meters` ); diff --git a/libs/metering/src/lib/usage.metrics.spec.ts b/libs/metering/src/lib/usage.metrics.spec.ts new file mode 100644 index 0000000..7020088 --- /dev/null +++ b/libs/metering/src/lib/usage.metrics.spec.ts @@ -0,0 +1,28 @@ +/* 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 { Registry } from '@prometheus-io/client'; + +import { UsageMetrics } from './usage.metrics'; +import { metricValues, zeroMetricValues } from '../testing'; + +describe('UsageMetrics', () => { + let registry: Registry; + + beforeEach(() => { + registry = new Registry(); + }); + + it('starts each usage source at zero', async () => { + new UsageMetrics(registry); + + expect(await metricValues(registry, 'metering_usage_source_total')).toEqual( + zeroMetricValues([ + { source: 'redis' }, + { source: 'clickhouse-not-populated' }, + { source: 'clickhouse-redis-error' }, + ]) + ); + }); +}); diff --git a/libs/metering/src/lib/usage.metrics.ts b/libs/metering/src/lib/usage.metrics.ts new file mode 100644 index 0000000..e540d08 --- /dev/null +++ b/libs/metering/src/lib/usage.metrics.ts @@ -0,0 +1,47 @@ +/* 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 } from '@nestjs/common'; +import type { Registry } from '@prometheus-io/client'; + +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; + +import { allOf, counter, initialize } from './utils/metrics'; + +export type UsageSource = + 'redis' | 'clickhouse-not-populated' | 'clickhouse-redis-error'; + +@Injectable() +export class UsageMetrics { + readonly source; + readonly published; + readonly publishErrors; + + constructor(@Inject(PrometheusRegistry) registry: Registry) { + this.source = counter( + registry, + 'metering_usage_source_total', + 'Window usage lookups by the source that answered', + ['source'] + ); + initialize( + this.source, + allOf({ + redis: true, + 'clickhouse-not-populated': true, + 'clickhouse-redis-error': true, + }).map((source) => ({ source })) + ); + this.published = counter( + registry, + 'metering_publisher_published_total', + 'Usage events published to Pub/Sub' + ); + this.publishErrors = counter( + registry, + 'metering_publisher_errors_total', + 'Usage events that failed to publish' + ); + } +} diff --git a/libs/metering/src/lib/usage.service.spec.ts b/libs/metering/src/lib/usage.service.spec.ts index baf49b0..8dddd59 100644 --- a/libs/metering/src/lib/usage.service.spec.ts +++ b/libs/metering/src/lib/usage.service.spec.ts @@ -4,6 +4,7 @@ import { Logger, type LoggerService } from '@nestjs/common'; import { Test } from '@nestjs/testing'; +import { Registry } from '@prometheus-io/client'; import { MeteringConfigurationManager, @@ -13,6 +14,7 @@ import { StatsDService, type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; import { IngestUsageRequestFactory, @@ -28,9 +30,11 @@ import { TimestampOutOfRangeError, UsageCountersError, } from './metering.error'; +import { UsageMetrics } from './usage.metrics'; import { UsageCountersManager } from './usage-counters.manager'; import { UsageGrantsManager } from './usage-grants.manager'; import { UsageService } from './usage.service'; +import { incrementedMetricValues } from '../testing'; const CLIENT_ID = 'vpn'; const NOW = new Date('2026-05-15T12:00:00.000Z'); @@ -56,9 +60,11 @@ describe('UsageService', () => { Pick >; let statsd: jest.Mocked>; + let registry: Registry; let logger: jest.Mocked>; beforeEach(async () => { + registry = new Registry(); meteringConfigurationManager = { getMeterBySlug: jest.fn() }; meteringPublisherManager = { publish: jest.fn().mockResolvedValue(undefined), @@ -94,6 +100,8 @@ describe('UsageService', () => { { provide: UsageCountersManager, useValue: usageCountersManager }, { provide: UsageGrantsManager, useValue: usageGrantsManager }, { provide: StatsDService, useValue: statsd }, + { provide: PrometheusRegistry, useValue: registry }, + UsageMetrics, { provide: Logger, useValue: logger }, ], }).compile(); @@ -298,6 +306,25 @@ describe('UsageService', () => { }); }); + it('records Redis as the usage source in Prometheus', async () => { + const meter = monthlyMeter(); + meteringConfigurationManager.getMeterBySlug.mockResolvedValue(meter); + usageCountersManager.findWindowUsage.mockResolvedValue({ + ...MONTHLY_WINDOW, + usage: 250, + }); + + await usageService.queryUsage( + CLIENT_ID, + UsageQueryParamsFactory({ slug: meter.slug }), + NOW + ); + + expect( + await incrementedMetricValues(registry, 'metering_usage_source_total') + ).toEqual([{ value: 1, labels: { source: 'redis' } }]); + }); + it('raises the reported limit by the active granted amount', async () => { const meter = monthlyMeter(); const params = UsageQueryParamsFactory({ slug: meter.slug }); @@ -370,6 +397,23 @@ describe('UsageService', () => { }); }); + it('records the ClickHouse read as the usage source in Prometheus', async () => { + const meter = monthlyMeter(); + meteringConfigurationManager.getMeterBySlug.mockResolvedValue(meter); + + await usageService.queryUsage( + CLIENT_ID, + UsageQueryParamsFactory({ slug: meter.slug }), + NOW + ); + + expect( + await incrementedMetricValues(registry, 'metering_usage_source_total') + ).toEqual([ + { value: 1, labels: { source: 'clickhouse-not-populated' } }, + ]); + }); + it('reads a sliding window that ends at the end of the current hour', async () => { const meter = StrapiMeterFactory({ window: { kind: 'sliding', durationMs: 5 * 60 * 60 * 1000 }, @@ -507,6 +551,21 @@ describe('UsageService', () => { source: 'clickhouse-redis-error', }); }); + + it('records the Redis failure as the usage source in Prometheus', async () => { + const meter = monthlyMeter(); + meteringConfigurationManager.getMeterBySlug.mockResolvedValue(meter); + + await usageService.queryUsage( + CLIENT_ID, + UsageQueryParamsFactory({ slug: meter.slug }), + NOW + ); + + expect( + await incrementedMetricValues(registry, 'metering_usage_source_total') + ).toEqual([{ value: 1, labels: { source: 'clickhouse-redis-error' } }]); + }); }); it('rejects unknown slugs with MeterNotConfiguredError', async () => { diff --git a/libs/metering/src/lib/usage.service.ts b/libs/metering/src/lib/usage.service.ts index 2bb8661..abd1ebe 100644 --- a/libs/metering/src/lib/usage.service.ts +++ b/libs/metering/src/lib/usage.service.ts @@ -13,6 +13,7 @@ import { type StatsD, } from '@entitlements/shared/metrics/statsd'; +import { UsageMetrics } from './usage.metrics'; import { MeteringEventsManager } from './metering-events.manager'; import { MeteringPublisherManager } from './metering-publisher.manager'; import { MeteringSweepManager } from './metering-sweep.manager'; @@ -39,6 +40,7 @@ export class UsageService { private readonly usageCountersManager: UsageCountersManager, private readonly usageGrantsManager: UsageGrantsManager, @Inject(StatsDService) private readonly statsd: StatsD, + private readonly metrics: UsageMetrics, @Inject(Logger) private readonly logger: LoggerService ) {} @@ -116,15 +118,18 @@ export class UsageService { ); if (counted) { this.statsd.increment('metering.usage.source', { source: 'redis' }); + this.metrics.source.inc({ source: 'redis' }); return counted; } this.statsd.increment('metering.usage.source', { source: 'clickhouse-not-populated', }); + this.metrics.source.inc({ source: 'clickhouse-not-populated' }); } catch (err) { this.statsd.increment('metering.usage.source', { source: 'clickhouse-redis-error', }); + this.metrics.source.inc({ source: 'clickhouse-redis-error' }); this.logger.error(err); } return this.findWindowUsageInClickHouse(key, window, now); diff --git a/libs/metering/src/lib/utils/metrics.ts b/libs/metering/src/lib/utils/metrics.ts new file mode 100644 index 0000000..247abf8 --- /dev/null +++ b/libs/metering/src/lib/utils/metrics.ts @@ -0,0 +1,59 @@ +/* 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 { + Counter, + Gauge, + Histogram, + type LabelValues, + type Registry, +} from '@prometheus-io/client'; + +/** Buckets for job durations, up to the sweep's ~15 minute shutdown grace. */ +const JOB_DURATION_BUCKETS = [0.1, 0.5, 1, 5, 15, 30, 60, 120, 300, 600, 900]; + +/** Lists every member of `T`; the `Record` fails to compile if one is missing. */ +export const allOf = (members: Record): T[] => + Object.keys(members) as T[]; + +/** + * Starts each label combination at 0. A series that first appears at 1 hides + * that increment from `increase()` and `rate()`, so rare events read as none. + */ +export const initialize = ( + metric: Counter, + combinations: LabelValues[] +): void => { + for (const labels of combinations) { + metric.inc(labels, 0); + } +}; + +export const counter = ( + registry: Registry, + name: string, + help: string, + labelNames: readonly L[] = [] +) => new Counter({ name, help, labelNames, registers: [registry] }); + +export const gauge = ( + registry: Registry, + name: string, + help: string, + labelNames: readonly L[] = [] +) => new Gauge({ name, help, labelNames, registers: [registry] }); + +export const jobHistogram = ( + registry: Registry, + name: string, + help: string, + labelNames: readonly L[] = [] +) => + new Histogram({ + name, + help, + labelNames, + buckets: JOB_DURATION_BUCKETS, + registers: [registry], + }); diff --git a/libs/metering/src/testing.ts b/libs/metering/src/testing.ts index dd40306..39d147e 100644 --- a/libs/metering/src/testing.ts +++ b/libs/metering/src/testing.ts @@ -4,6 +4,7 @@ import 'reflect-metadata'; +import { type MetricValueWithName, Registry } from '@prometheus-io/client'; import { RateLimiterMemory } from 'rate-limiter-flexible'; import { StatsD } from '@entitlements/shared/metrics/statsd'; @@ -16,6 +17,7 @@ import { SESSIONS_TABLE, WATERMARKS_TABLE, } from './lib/metering.constants'; +import { ClickHouseMetrics } from './lib/clickhouse.metrics'; import type { ClickHouseRateLimiters, MeteringRedisPipeline, @@ -92,10 +94,33 @@ export function integrationClickHouseRateLimiters(): ClickHouseRateLimiters { }; } +export function testMetrics(Metrics: new (registry: Registry) => T): { + registry: Registry; + metrics: T; +} { + const registry = new Registry(); + return { registry, metrics: new Metrics(registry) }; +} + +/** The recorded samples of one metric, without histogram buckets. */ +export async function metricValues( + registry: Registry, + name: string +): Promise[]> { + const metric = await registry.getSingleMetric(name)?.get(); + if (!metric) { + throw new Error(`metric ${name} is not registered`); + } + return (metric.values as MetricValueWithName[]).filter( + ({ metricName }) => !metricName?.endsWith('_bucket') + ); +} + export function integrationClickHouseClient(): ClickHouseClient { return new ClickHouseClient( INTEGRATION_CLICKHOUSE_CONFIG, new StatsD({ mock: true }), + new ClickHouseMetrics(new Registry()), integrationClickHouseRateLimiters() ); } @@ -159,3 +184,20 @@ export function withSentryCronWrapper< }, }; } + +/** The samples of one metric that were incremented, so not still at their initial 0. */ +export async function incrementedMetricValues( + registry: Registry, + name: string +): Promise[]> { + return (await metricValues(registry, name)).filter( + ({ value }) => value !== 0 + ); +} + +/** The samples `metricValues` returns for series that were never incremented. */ +export function zeroMetricValues( + labels: Record[] +): { value: number; labels: Record }[] { + return labels.map((label) => ({ value: 0, labels: label })); +} diff --git a/libs/shared/cms/src/lib/metering-configuration.manager.spec.ts b/libs/shared/cms/src/lib/metering-configuration.manager.spec.ts index 4bbd424..3c44e5e 100644 --- a/libs/shared/cms/src/lib/metering-configuration.manager.spec.ts +++ b/libs/shared/cms/src/lib/metering-configuration.manager.spec.ts @@ -5,6 +5,7 @@ import { Test } from '@nestjs/testing'; import { DocumentNode } from 'graphql'; import { StatsD } from 'hot-shots'; +import { type MetricValueWithName, Registry } from '@prometheus-io/client'; import { StrapiClient, @@ -14,6 +15,7 @@ import { StrapiMeterRawFactory, toStrapiMeter, } from '@entitlements/shared/cms'; +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; import { StatsDService } from '@entitlements/shared/metrics/statsd'; import { MeteringConfigurationManager } from './metering-configuration.manager'; @@ -60,8 +62,10 @@ describe('MeteringConfigurationManager', () => { let manager: MeteringConfigurationManager; let mockStrapiClient: jest.Mocked>; let mockStatsd: jest.Mocked>; + let registry: Registry; beforeEach(async () => { + registry = new Registry(); mockStatsd = { timing: jest.fn(), }; @@ -75,6 +79,7 @@ describe('MeteringConfigurationManager', () => { providers: [ MeteringConfigurationManager, { provide: StatsDService, useValue: mockStatsd }, + { provide: PrometheusRegistry, useValue: registry }, { provide: StrapiClient, useValue: mockStrapiClient }, ], }).compile(); @@ -150,6 +155,68 @@ describe('MeteringConfigurationManager', () => { } ); }); + + describe('request duration histogram', () => { + const observations = async () => + ( + await registry + .getSingleMetric('cms_metering_request_duration_seconds') + ?.get() + )?.values.filter((value: MetricValueWithName) => + value.metricName?.endsWith('_sum') + ); + + it('records the duration in seconds with the operation name', async () => { + manager.onStrapiClientResponse({ + method: 'query', + requestStartTime: 0, + requestEndTime: 250, + elapsed: 250, + cache: false, + cacheType: 'method', + query: {} as DocumentNode, + error: undefined, + }); + + expect(await observations()).toEqual([ + expect.objectContaining({ + value: 0.25, + labels: { + method: 'query', + error: 'false', + cache: 'false', + cache_type: 'method', + operation_name: 'MockOperation', + }, + }), + ]); + }); + + it('omits the operation name when there is no query', async () => { + manager.onStrapiClientResponse({ + method: 'query', + requestStartTime: 0, + requestEndTime: 250, + elapsed: 250, + cache: true, + cacheType: 'method', + query: undefined, + error: new Error('Test error'), + }); + + expect(await observations()).toEqual([ + expect.objectContaining({ + value: 0.25, + labels: { + method: 'query', + error: 'true', + cache: 'true', + cache_type: 'method', + }, + }), + ]); + }); + }); }); describe('getMeterBySlug', () => { diff --git a/libs/shared/cms/src/lib/metering-configuration.manager.ts b/libs/shared/cms/src/lib/metering-configuration.manager.ts index ed8a0a8..e8e0919 100644 --- a/libs/shared/cms/src/lib/metering-configuration.manager.ts +++ b/libs/shared/cms/src/lib/metering-configuration.manager.ts @@ -5,7 +5,9 @@ import { getOperationName } from '@apollo/client/utilities'; import { Inject, Injectable } from '@nestjs/common'; import { StatsD } from 'hot-shots'; +import { Histogram, type Registry } from '@prometheus-io/client'; +import { PrometheusRegistry } from '@entitlements/shared/metrics/prometheus'; import { StatsDService } from '@entitlements/shared/metrics/statsd'; import { MeterBySlugResultUtil, meterBySlugQuery } from './queries/meter'; import type { StrapiMeter } from './queries/meter'; @@ -15,11 +17,22 @@ import type { MeterBySlugQuery } from '../__generated__/graphql'; @Injectable() export class MeteringConfigurationManager { + private readonly requestDuration: Histogram< + 'method' | 'error' | 'cache' | 'cache_type' | 'operation_name' + >; + constructor( private strapiClient: StrapiClient, @Inject(StatsDService) - private statsd: StatsD + private statsd: StatsD, + @Inject(PrometheusRegistry) registry: Registry ) { + this.requestDuration = new Histogram({ + name: 'cms_metering_request_duration_seconds', + help: 'Duration of a Strapi request for meter configuration', + labelNames: ['method', 'error', 'cache', 'cache_type', 'operation_name'], + registers: [registry], + }); this.strapiClient.on('response', this.onStrapiClientResponse.bind(this)); } @@ -40,6 +53,16 @@ export class MeteringConfigurationManager { undefined, tags ); + this.requestDuration.observe( + { + method: response.method, + error: defaultTags.error, + cache: defaultTags.cache, + cache_type: defaultTags.cacheType, + ...(operationName && { operation_name: operationName }), + }, + response.elapsed / 1000 + ); } async getMeterResultUtil(slug: string): Promise { diff --git a/libs/shared/metrics/prometheus/.eslintrc.json b/libs/shared/metrics/prometheus/.eslintrc.json new file mode 100644 index 0000000..af8a581 --- /dev/null +++ b/libs/shared/metrics/prometheus/.eslintrc.json @@ -0,0 +1,15 @@ +{ + "extends": ["../../../../.eslintrc.json"], + "ignorePatterns": ["!**/*"], + "overrides": [ + { + "files": ["*.ts"], + "rules": {} + }, + { + "files": ["*.json"], + "parser": "jsonc-eslint-parser", + "rules": {} + } + ] +} diff --git a/libs/shared/metrics/prometheus/.swcrc b/libs/shared/metrics/prometheus/.swcrc new file mode 100644 index 0000000..f52b4e4 --- /dev/null +++ b/libs/shared/metrics/prometheus/.swcrc @@ -0,0 +1,14 @@ +{ + "jsc": { + "target": "es2017", + "parser": { + "syntax": "typescript", + "decorators": true, + "dynamicImport": true + }, + "transform": { + "decoratorMetadata": true, + "legacyDecorator": true + } + } +} diff --git a/libs/shared/metrics/prometheus/README.md b/libs/shared/metrics/prometheus/README.md new file mode 100644 index 0000000..ed39510 --- /dev/null +++ b/libs/shared/metrics/prometheus/README.md @@ -0,0 +1,5 @@ +# shared-metrics-prometheus + +Add `PrometheusRegistryProvider` and `PrometheusServer` to an app's providers, and `PrometheusConfig` to its `RootConfig`. The server serves the registry on `GET /metrics` on its own port (`PROMETHEUS_CONFIG__PORT`, default 9464), separate from the app's HTTP port. Keep that port in-cluster: it must not be exposed through an ingress. + +Define metrics on the registry injected via `PrometheusRegistry`. HTTP apps can apply `PrometheusRouteMiddleware` to count and time requests. diff --git a/libs/shared/metrics/prometheus/jest.config.ts b/libs/shared/metrics/prometheus/jest.config.ts new file mode 100644 index 0000000..f13ec42 --- /dev/null +++ b/libs/shared/metrics/prometheus/jest.config.ts @@ -0,0 +1,27 @@ +import { Config } from 'jest'; +/* eslint-disable */ +import { readFileSync } from 'fs'; + +// Reading the SWC compilation config and remove the "exclude" +// for the test files to be compiled by SWC +const { exclude: _, ...swcJestConfig } = JSON.parse( + readFileSync(`${__dirname}/.swcrc`, 'utf-8') +); + +// disable .swcrc look-up by SWC core because we're passing in swcJestConfig ourselves. +// If we do not disable this, SWC Core will read .swcrc and won't transform our test files due to "exclude" +if (swcJestConfig.swcrc === undefined) { + swcJestConfig.swcrc = false; +} + +const config: Config = { + displayName: 'shared-metrics-prometheus', + preset: '../../../../jest.preset.js', + transform: { + '^.+\\.[tj]s$': ['@swc/jest', swcJestConfig], + }, + moduleFileExtensions: ['ts', 'js', 'html'], + testEnvironment: 'node', + coverageDirectory: '../../../../coverage/libs/shared/metrics/prometheus', +}; +export default config; diff --git a/libs/shared/metrics/prometheus/package.json b/libs/shared/metrics/prometheus/package.json new file mode 100644 index 0000000..2e6c147 --- /dev/null +++ b/libs/shared/metrics/prometheus/package.json @@ -0,0 +1,4 @@ +{ + "name": "@entitlements/shared/metrics/prometheus", + "version": "0.0.0" +} diff --git a/libs/shared/metrics/prometheus/project.json b/libs/shared/metrics/prometheus/project.json new file mode 100644 index 0000000..e1d9008 --- /dev/null +++ b/libs/shared/metrics/prometheus/project.json @@ -0,0 +1,35 @@ +{ + "name": "shared-metrics-prometheus", + "$schema": "../../../../node_modules/nx/schemas/project-schema.json", + "sourceRoot": "libs/shared/metrics/prometheus/src", + "projectType": "library", + "tags": ["scope:lib"], + "targets": { + "lint": { + "executor": "@nx/eslint:lint", + "outputs": ["{options.outputFile}"], + "options": { + "lintFilePatterns": [ + "libs/shared/metrics/prometheus/**/*.ts", + "libs/shared/metrics/prometheus/package.json" + ] + } + }, + "typecheck": { + "executor": "nx:run-commands", + "options": { + "commands": [ + "tsc --noEmit -p libs/shared/metrics/prometheus/tsconfig.lib.json", + "tsc --noEmit -p libs/shared/metrics/prometheus/tsconfig.spec.json" + ] + } + }, + "test-unit": { + "executor": "@nx/jest:jest", + "outputs": ["{workspaceRoot}/coverage/{projectRoot}"], + "options": { + "jestConfig": "libs/shared/metrics/prometheus/jest.config.ts" + } + } + } +} diff --git a/libs/shared/metrics/prometheus/src/index.ts b/libs/shared/metrics/prometheus/src/index.ts new file mode 100644 index 0000000..cc2d65f --- /dev/null +++ b/libs/shared/metrics/prometheus/src/index.ts @@ -0,0 +1,8 @@ +/* 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/. */ + +export * from './lib/prometheus.config'; +export * from './lib/prometheus.registry'; +export * from './lib/prometheus.server'; +export * from './lib/prometheus-route.middleware'; diff --git a/libs/shared/metrics/prometheus/src/lib/prometheus-route.middleware.spec.ts b/libs/shared/metrics/prometheus/src/lib/prometheus-route.middleware.spec.ts new file mode 100644 index 0000000..a66c1a6 --- /dev/null +++ b/libs/shared/metrics/prometheus/src/lib/prometheus-route.middleware.spec.ts @@ -0,0 +1,118 @@ +/* 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 'node:events'; +import type { NextFunction, Request, Response } from 'express'; +import { type MetricValueWithName, Registry } from '@prometheus-io/client'; + +import { + PrometheusRouteMiddleware, + normalizeRoute, +} from './prometheus-route.middleware'; + +type FakeResponse = Response & { finish: () => void }; + +const buildRequest = (overrides: Partial = {}): Request => + ({ method: 'GET', path: '/some/path', ...overrides }) as unknown as Request; + +const buildResponse = (statusCode = 200): FakeResponse => { + const emitter = new EventEmitter(); + return Object.assign(emitter, { + statusCode, + finish: () => emitter.emit('finish'), + }) as unknown as FakeResponse; +}; + +describe('PrometheusRouteMiddleware', () => { + let registry: Registry; + let middleware: PrometheusRouteMiddleware; + let next: jest.MockedFunction; + + const requestCount = async () => + (await registry.getSingleMetric('http_server_requests_total')?.get()) + ?.values; + const durationCount = async () => + ( + await registry + .getSingleMetric('http_server_request_duration_seconds') + ?.get() + )?.values.filter((value: MetricValueWithName) => + value.metricName?.endsWith('_count') + ); + + beforeEach(() => { + registry = new Registry(); + middleware = new PrometheusRouteMiddleware(registry); + next = jest.fn(); + }); + + it('calls next', () => { + middleware.use(buildRequest(), buildResponse(), next); + + expect(next).toHaveBeenCalledTimes(1); + }); + + it('records nothing until the response finishes', async () => { + middleware.use(buildRequest(), buildResponse(), next); + + expect(await requestCount()).toEqual([]); + }); + + describe('when the response finishes', () => { + beforeEach(() => { + const res = buildResponse(201); + middleware.use( + buildRequest({ + method: 'POST', + route: { path: '/v1/usage' }, + } as Partial), + res, + next + ); + res.finish(); + }); + + it('counts the request by method, route and status code', async () => { + expect(await requestCount()).toEqual([ + { + value: 1, + labels: { method: 'POST', route: 'v1/usage', status_code: '201' }, + }, + ]); + }); + + it('times the request with the same labels', async () => { + expect(await durationCount()).toEqual([ + expect.objectContaining({ + value: 1, + labels: { method: 'POST', route: 'v1/usage', status_code: '201' }, + }), + ]); + }); + }); + + it('labels a request with no matched route as unmatched', async () => { + const res = buildResponse(404); + middleware.use(buildRequest(), res, next); + res.finish(); + + expect(await requestCount()).toEqual([ + { + value: 1, + labels: { method: 'GET', route: 'unmatched', status_code: '404' }, + }, + ]); + }); +}); + +describe('normalizeRoute', () => { + it.each([ + { path: '/v1/usage/:slug', expected: 'v1/usage/:slug' }, + { path: '/', expected: 'root' }, + { path: undefined, expected: 'unmatched' }, + { path: '', expected: 'unmatched' }, + ])('maps $path to $expected', ({ path, expected }) => { + expect(normalizeRoute(path)).toBe(expected); + }); +}); diff --git a/libs/shared/metrics/prometheus/src/lib/prometheus-route.middleware.ts b/libs/shared/metrics/prometheus/src/lib/prometheus-route.middleware.ts new file mode 100644 index 0000000..e54266a --- /dev/null +++ b/libs/shared/metrics/prometheus/src/lib/prometheus-route.middleware.ts @@ -0,0 +1,64 @@ +/* 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 { Counter, Histogram, type Registry } from '@prometheus-io/client'; + +import { PrometheusRegistry } from './prometheus.registry'; + +const LABELS = ['method', 'route', 'status_code'] as const; + +/** + * Counts and times every HTTP response, labelled by method, Express route + * pattern (or `unmatched`) and status code. Runs before Nest's guards, so + * auth failures and validation errors are included. + */ +@Injectable() +export class PrometheusRouteMiddleware implements NestMiddleware { + private readonly requests: Counter<(typeof LABELS)[number]>; + private readonly duration: Histogram<(typeof LABELS)[number]>; + + constructor(@Inject(PrometheusRegistry) registry: Registry) { + this.requests = new Counter({ + name: 'http_server_requests_total', + help: 'HTTP responses sent', + labelNames: LABELS, + registers: [registry], + }); + this.duration = new Histogram({ + name: 'http_server_request_duration_seconds', + help: 'Time from request entry until the response finished', + labelNames: LABELS, + registers: [registry], + }); + } + + use(req: Request, res: Response, next: NextFunction) { + const stopTimer = this.duration.startTimer(); + + res.on('finish', () => { + const labels = { + method: req.method, + route: normalizeRoute(req.route?.path), + status_code: String(res.statusCode), + }; + this.requests.inc(labels); + stopTimer(labels); + }); + + 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'; +}; diff --git a/libs/shared/metrics/prometheus/src/lib/prometheus.config.spec.ts b/libs/shared/metrics/prometheus/src/lib/prometheus.config.spec.ts new file mode 100644 index 0000000..05f724a --- /dev/null +++ b/libs/shared/metrics/prometheus/src/lib/prometheus.config.spec.ts @@ -0,0 +1,35 @@ +/* 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 'reflect-metadata'; + +import { plainToClass } from 'class-transformer'; +import { validateSync } from 'class-validator'; + +import { PrometheusConfig } from './prometheus.config'; + +const validate = (raw: Record) => { + const config = plainToClass(PrometheusConfig, raw, { + exposeDefaultValues: true, + }); + return { config, errors: validateSync(config) }; +}; + +describe('PrometheusConfig', () => { + it('defaults the port to 9464', () => { + expect(validate({}).config.port).toBe(9464); + }); + + it('parses a configured port', () => { + expect(validate({ port: '9500' }).config.port).toBe(9500); + }); + + it('accepts a configured port', () => { + expect(validate({ port: '9500' }).errors).toEqual([]); + }); + + it.each(['0', '65536', 'abc'])('rejects port %s', (port) => { + expect(validate({ port }).errors).toHaveLength(1); + }); +}); diff --git a/libs/shared/metrics/prometheus/src/lib/prometheus.config.ts b/libs/shared/metrics/prometheus/src/lib/prometheus.config.ts new file mode 100644 index 0000000..ac8047d --- /dev/null +++ b/libs/shared/metrics/prometheus/src/lib/prometheus.config.ts @@ -0,0 +1,14 @@ +/* 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 { IsInt, Max, Min } from 'class-validator'; + +export class PrometheusConfig { + @Type(() => Number) + @IsInt() + @Min(1) + @Max(65535) + public readonly port: number = 9464; +} diff --git a/libs/shared/metrics/prometheus/src/lib/prometheus.registry.spec.ts b/libs/shared/metrics/prometheus/src/lib/prometheus.registry.spec.ts new file mode 100644 index 0000000..567a7a9 --- /dev/null +++ b/libs/shared/metrics/prometheus/src/lib/prometheus.registry.spec.ts @@ -0,0 +1,23 @@ +/* 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 { FactoryProvider } from '@nestjs/common'; +import type { Registry } from '@prometheus-io/client'; + +import { PrometheusRegistryProvider } from './prometheus.registry'; + +describe('PrometheusRegistryProvider', () => { + const create = () => + ( + PrometheusRegistryProvider as FactoryProvider + ).useFactory() as Registry; + + it('collects the default process metrics', async () => { + expect(await create().metrics()).toContain('process_cpu_seconds_total'); + }); + + it('creates a separate registry each time', () => { + expect(create()).not.toBe(create()); + }); +}); diff --git a/libs/shared/metrics/prometheus/src/lib/prometheus.registry.ts b/libs/shared/metrics/prometheus/src/lib/prometheus.registry.ts new file mode 100644 index 0000000..acd4f95 --- /dev/null +++ b/libs/shared/metrics/prometheus/src/lib/prometheus.registry.ts @@ -0,0 +1,17 @@ +/* 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 { Provider } from '@nestjs/common'; +import { Registry, collectDefaultMetrics } from '@prometheus-io/client'; + +export const PrometheusRegistry = Symbol('PROMETHEUS_REGISTRY'); + +export const PrometheusRegistryProvider: Provider = { + provide: PrometheusRegistry, + useFactory: () => { + const registry = new Registry(); + collectDefaultMetrics({ register: registry }); + return registry; + }, +}; diff --git a/libs/shared/metrics/prometheus/src/lib/prometheus.server.spec.ts b/libs/shared/metrics/prometheus/src/lib/prometheus.server.spec.ts new file mode 100644 index 0000000..76c6bee --- /dev/null +++ b/libs/shared/metrics/prometheus/src/lib/prometheus.server.spec.ts @@ -0,0 +1,123 @@ +/* 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 { LoggerService } from '@nestjs/common'; +import { Counter, Registry } from '@prometheus-io/client'; + +import { PrometheusConfig } from './prometheus.config'; +import { PrometheusServer } from './prometheus.server'; + +describe('PrometheusServer', () => { + let registry: Registry; + let logger: jest.Mocked>; + let server: PrometheusServer; + + const url = (path: string) => `http://127.0.0.1:${server.port}${path}`; + + beforeEach(async () => { + registry = new Registry(); + new Counter({ + name: 'test_events_total', + help: 'Test events', + registers: [registry], + }).inc(3); + logger = { log: jest.fn(), error: jest.fn() }; + server = new PrometheusServer( + { port: 0 } as PrometheusConfig, + registry, + logger as unknown as LoggerService + ); + await server.onApplicationBootstrap(); + }); + + afterEach(async () => { + await server.onApplicationShutdown(); + }); + + it('logs the port it serves metrics on', () => { + expect(logger.log).toHaveBeenCalledWith( + `Serving metrics on port ${server.port}`, + 'PrometheusServer' + ); + }); + + describe('GET /metrics', () => { + it('responds 200', async () => { + expect((await fetch(url('/metrics'))).status).toBe(200); + }); + + it('responds with the Prometheus content type', async () => { + const res = await fetch(url('/metrics')); + + expect(res.headers.get('content-type')).toBe(registry.contentType); + }); + + it('responds with the registry metrics', async () => { + const res = await fetch(url('/metrics')); + + expect(await res.text()).toContain('test_events_total 3'); + }); + + it('ignores a query string', async () => { + expect((await fetch(url('/metrics?x=1'))).status).toBe(200); + }); + }); + + it.each(['/', '/__heartbeat__', '/metrics/extra'])( + 'responds 404 for GET %s', + async (path) => { + expect((await fetch(url(path))).status).toBe(404); + } + ); + + it('responds 404 for POST /metrics', async () => { + expect((await fetch(url('/metrics'), { method: 'POST' })).status).toBe(404); + }); + + describe('when collecting metrics fails', () => { + const failure = new Error('collect failed'); + + beforeEach(() => { + jest.spyOn(registry, 'metrics').mockRejectedValue(failure); + }); + + it('responds 500', async () => { + expect((await fetch(url('/metrics'))).status).toBe(500); + }); + + it('logs the error', async () => { + await fetch(url('/metrics')); + + expect(logger.error).toHaveBeenCalledWith(failure, 'PrometheusServer'); + }); + }); + + it('stops accepting connections on shutdown', async () => { + const target = url('/metrics'); + + await server.onApplicationShutdown(); + + await expect(fetch(target)).rejects.toThrow(); + }); + + it('shuts down when it never started', async () => { + const idle = new PrometheusServer( + { port: 0 } as PrometheusConfig, + registry, + logger as unknown as LoggerService + ); + + await expect(idle.onApplicationShutdown()).resolves.toBeUndefined(); + }); + + it('fails to start when the port is taken', async () => { + const clash = new PrometheusServer( + { port: server.port } as PrometheusConfig, + registry, + logger as unknown as LoggerService + ); + + await expect(clash.onApplicationBootstrap()).rejects.toThrow('EADDRINUSE'); + }); +}); diff --git a/libs/shared/metrics/prometheus/src/lib/prometheus.server.ts b/libs/shared/metrics/prometheus/src/lib/prometheus.server.ts new file mode 100644 index 0000000..fc9a64a --- /dev/null +++ b/libs/shared/metrics/prometheus/src/lib/prometheus.server.ts @@ -0,0 +1,82 @@ +/* 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 { once } from 'node:events'; +import { + createServer, + type IncomingMessage, + type Server, + type ServerResponse, +} from 'node:http'; +import type { AddressInfo } from 'node:net'; +import { + Inject, + Injectable, + Logger, + type LoggerService, + OnApplicationBootstrap, + OnApplicationShutdown, +} from '@nestjs/common'; +import type { Registry } from '@prometheus-io/client'; + +import { PrometheusConfig } from './prometheus.config'; +import { PrometheusRegistry } from './prometheus.registry'; + +/** + * Serves `GET /metrics` on its own port, outside the Nest HTTP app, so the + * endpoint never sits behind the app's ingress, guards or middleware. + */ +@Injectable() +export class PrometheusServer + implements OnApplicationBootstrap, OnApplicationShutdown +{ + private readonly server: Server; + + constructor( + private readonly config: PrometheusConfig, + @Inject(PrometheusRegistry) private readonly registry: Registry, + @Inject(Logger) private readonly logger: LoggerService + ) { + this.server = createServer((req, res) => void this.handle(req, res)); + } + + get port(): number { + return (this.server.address() as AddressInfo).port; + } + + async onApplicationBootstrap(): Promise { + this.server.listen(this.config.port); + await once(this.server, 'listening'); + this.logger.log( + `Serving metrics on port ${this.port}`, + PrometheusServer.name + ); + } + + async onApplicationShutdown(): Promise { + if (!this.server.listening) return; + const closed = once(this.server, 'close'); + this.server.close(); + this.server.closeAllConnections(); + await closed; + } + + private async handle( + req: IncomingMessage, + res: ServerResponse + ): Promise { + if (req.method !== 'GET' || req.url?.split('?')[0] !== '/metrics') { + res.writeHead(404).end(); + return; + } + try { + const body = await this.registry.metrics(); + res.writeHead(200, { 'Content-Type': this.registry.contentType }); + res.end(body); + } catch (err) { + this.logger.error(err, PrometheusServer.name); + res.writeHead(500).end(); + } + } +} diff --git a/libs/shared/metrics/prometheus/tsconfig.json b/libs/shared/metrics/prometheus/tsconfig.json new file mode 100644 index 0000000..2c9d3a5 --- /dev/null +++ b/libs/shared/metrics/prometheus/tsconfig.json @@ -0,0 +1,16 @@ +{ + "extends": "../../../../tsconfig.base.json", + "compilerOptions": { + "module": "commonjs" + }, + "files": [], + "include": [], + "references": [ + { + "path": "./tsconfig.lib.json" + }, + { + "path": "./tsconfig.spec.json" + } + ] +} diff --git a/libs/shared/metrics/prometheus/tsconfig.lib.json b/libs/shared/metrics/prometheus/tsconfig.lib.json new file mode 100644 index 0000000..28369ef --- /dev/null +++ b/libs/shared/metrics/prometheus/tsconfig.lib.json @@ -0,0 +1,11 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "module": "commonjs", + "outDir": "../../../../dist/out-tsc", + "declaration": true, + "types": ["node"] + }, + "exclude": ["jest.config.ts", "src/**/*.spec.ts", "src/**/*.test.ts"], + "include": ["src/**/*.ts"] +} diff --git a/libs/shared/metrics/prometheus/tsconfig.spec.json b/libs/shared/metrics/prometheus/tsconfig.spec.json new file mode 100644 index 0000000..6668655 --- /dev/null +++ b/libs/shared/metrics/prometheus/tsconfig.spec.json @@ -0,0 +1,14 @@ +{ + "extends": "./tsconfig.json", + "compilerOptions": { + "outDir": "../../../../dist/out-tsc", + "module": "commonjs", + "types": ["jest", "node"] + }, + "include": [ + "jest.config.ts", + "src/**/*.test.ts", + "src/**/*.spec.ts", + "src/**/*.d.ts" + ] +} diff --git a/libs/shared/metrics/statsd/src/lib/statsd-route.middleware.ts b/libs/shared/metrics/statsd/src/lib/statsd-route.middleware.ts index ca27b99..9266049 100644 --- a/libs/shared/metrics/statsd/src/lib/statsd-route.middleware.ts +++ b/libs/shared/metrics/statsd/src/lib/statsd-route.middleware.ts @@ -13,6 +13,8 @@ import { import type { NextFunction, Request, Response } from 'express'; import { StatsD } from 'hot-shots'; +import { normalizeRoute } from '@entitlements/shared/metrics/prometheus'; + import { StatsDService } from './statsd.provider'; /** @@ -80,14 +82,3 @@ export class StatsDRouteMiddleware implements NestMiddleware { 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'; -}; diff --git a/package.json b/package.json index cbd6031..d8e590d 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "@nestjs/platform-express": "^11.2.10", "@nestjs/schedule": "12.0.4", "@nestjs/swagger": "^11.4.8", + "@prometheus-io/client": "0.16.1", "@sentry/core": "^11.16.0", "@sentry/nestjs": "^11.16.0", "@sentry/node": "^11.16.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 6e93079..4b9ba98 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -202,6 +202,9 @@ importers: '@nestjs/swagger': specifier: ^11.4.8 version: 11.4.8(@nestjs/common@11.2.10(class-transformer@0.5.1)(class-validator@0.14.1)(reflect-metadata@0.2.2)(rxjs@7.8.2)(supports-color@8.1.1))(@nestjs/core@11.2.10)(class-transformer@0.5.1)(class-validator@0.14.1)(reflect-metadata@0.2.2) + '@prometheus-io/client': + specifier: 0.16.1 + version: 0.16.1 '@sentry/core': specifier: ^11.16.0 version: 11.16.0 @@ -2472,6 +2475,10 @@ packages: resolution: {integrity: sha512-//0sR/cow/s4ICQaYoAobOl4aU8cjU6x/V24V7XkKotb9+O+3zySIYp146vpaobYHnxa4pZX8NkV54Z5AwbDKA==} engines: {node: '>=12'} + '@prometheus-io/client@0.16.1': + resolution: {integrity: sha512-XkFPsGFGoSs/UMg/vh0QLDpanl/tsrOV5PLHdpGe8Ho+ir/Llhytr15j6y8ZwLrpIGzK9gTVVpIalA6C4UjUZw==} + engines: {node: ^22 || ^24 || >=26} + '@protobufjs/aspromise@1.1.2': resolution: {integrity: sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==} @@ -3481,6 +3488,9 @@ packages: bindings@1.5.0: resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==} + bintrees@1.0.2: + resolution: {integrity: sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==} + bl@4.1.0: resolution: {integrity: sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w==} @@ -7246,6 +7256,9 @@ packages: tcp-port-used@1.0.3: resolution: {integrity: sha512-4CEQ3qRJYo+mtEbJ+OoQu3dF4TDkwaO3RDVC4UzP5cpAOIUWwuwPjD7sdxDFFqsMUjsXVVYBMlg/boAaloThMA==} + tdigest@0.1.3: + resolution: {integrity: sha512-zbRt+lT+/H4fRItHshczHErVCQnitJk8MfMT24MqFJf3YL7SJJPqGIGeuOdvxXxM/AHFzKBl7WoyaYwqO9s3Kw==} + teeny-request@9.0.0: resolution: {integrity: sha512-resvxdc6Mgb7YEThw6G6bExlXKkv6+YbuzGg9xuXxSgxJF7Ozs+o8Y9+2R3sArdWdW8nOokoQb1yrpFB0pQK2g==} engines: {node: '>=14'} @@ -10554,6 +10567,11 @@ snapshots: '@pnpm/network.ca-file': 1.0.2 config-chain: 1.1.13 + '@prometheus-io/client@0.16.1': + dependencies: + '@opentelemetry/api': 1.9.1 + tdigest: 0.1.3 + '@protobufjs/aspromise@1.1.2': {} '@protobufjs/base64@1.1.2': {} @@ -11664,6 +11682,8 @@ snapshots: file-uri-to-path: 1.0.0 optional: true + bintrees@1.0.2: {} + bl@4.1.0: dependencies: buffer: 5.7.1 @@ -15904,6 +15924,10 @@ snapshots: transitivePeerDependencies: - supports-color + tdigest@0.1.3: + dependencies: + bintrees: 1.0.2 + teeny-request@9.0.0(supports-color@8.1.1): dependencies: http-proxy-agent: 5.0.0(supports-color@8.1.1) diff --git a/tsconfig.base.json b/tsconfig.base.json index 401c83b..17b61b2 100644 --- a/tsconfig.base.json +++ b/tsconfig.base.json @@ -45,6 +45,9 @@ ], "@entitlements/shared/error": ["./libs/shared/error/src/index.ts"], "@entitlements/shared/locks": ["./libs/shared/locks/src/index.ts"], + "@entitlements/shared/metrics/prometheus": [ + "./libs/shared/metrics/prometheus/src/index.ts" + ], "@entitlements/shared/metrics/statsd": [ "./libs/shared/metrics/statsd/src/index.ts" ],