Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,12 @@ Nx monorepo, pnpm, NestJS. Every app is built with webpack into `dist/apps/<app>
- `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/<path>` aliases from `tsconfig.base.json` (e.g., `@entitlements/shared/error`); avoid deep relative imports across library boundaries.
Expand Down
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
15 changes: 14 additions & 1 deletion apps/api/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { AppService } from './app.service';
import { RootConfigModule } from '../config/config.module';
import {
ClickHouseClient,
ClickHouseMetrics,
ClickHouseRateLimitersProvider,
MeteringAuthGuard,
MeteringEventsManager,
Expand All @@ -27,14 +28,21 @@ import {
UsageCountersManager,
UsageGrantsController,
UsageGrantsManager,
UsageGrantsMetrics,
UsageGrantsService,
UsageMetrics,
UsageService,
} from '@entitlements/metering';
import {
MeteringConfigurationManager,
StrapiClient,
} from '@entitlements/shared/cms';
import { FirestoreProvider } from '@entitlements/shared/db/firestore';
import {
PrometheusRegistryProvider,
PrometheusRouteMiddleware,
PrometheusServer,
} from '@entitlements/shared/metrics/prometheus';
import {
StatsDProvider,
StatsDRouteMiddleware,
Expand Down Expand Up @@ -64,6 +72,11 @@ import {
MeteringRedisClientProvider,
MeteringSweepManager,
MeteringSweepRepository,
ClickHouseMetrics,
UsageGrantsMetrics,
UsageMetrics,
PrometheusRegistryProvider,
PrometheusServer,
StatsDProvider,
StrapiClient,
UsageCountersManager,
Expand All @@ -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 },
Expand Down
5 changes: 5 additions & 0 deletions apps/api/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -35,6 +36,10 @@ export class RootConfig {
@IsDefined()
public readonly statsDConfig!: Partial<StatsDConfig>;

@Type(() => PrometheusConfig)
@ValidateNested()
public readonly prometheusConfig: PrometheusConfig = new PrometheusConfig();

@Type(() => SentryConfig)
@ValidateNested()
@IsDefined()
Expand Down
12 changes: 12 additions & 0 deletions apps/metering-metrics/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { SentryGlobalFilter, SentryModule } from '@sentry/nestjs/setup';

import {
ClickHouseClient,
ClickHouseMetrics,
ClickHouseRateLimitersProvider,
MeteringLockRedisClientProvider,
MeteringMetricsManager,
Expand All @@ -19,13 +20,19 @@ import {
MeteringSchedulerService,
MeteringSweepManager,
MeteringSweepRepository,
MetricsReportMetrics,
SchedulerMetrics,
} from '@entitlements/metering';
import {
MeteringConfigurationManager,
StrapiClient,
} 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,
Expand Down Expand Up @@ -64,6 +71,11 @@ import { AppService } from './app.service';
MeteringSchedulerService,
MeteringSweepManager,
MeteringSweepRepository,
ClickHouseMetrics,
MetricsReportMetrics,
SchedulerMetrics,
PrometheusRegistryProvider,
PrometheusServer,
StatsDProvider,
StrapiClient,
],
Expand Down
5 changes: 5 additions & 0 deletions apps/metering-metrics/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -32,6 +33,10 @@ export class RootConfig {
@IsDefined()
public readonly statsDConfig!: Partial<StatsDConfig>;

@Type(() => PrometheusConfig)
@ValidateNested()
public readonly prometheusConfig: PrometheusConfig = new PrometheusConfig();

@Type(() => SentryConfig)
@ValidateNested()
@IsDefined()
Expand Down
10 changes: 10 additions & 0 deletions apps/metering-subscriber/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,9 @@ import { AppService } from './app.service';
import { RootConfigModule } from '../config/config.module';
import {
ClickHouseClient,
ClickHouseMetrics,
ClickHouseRateLimitersProvider,
ConsumerMetrics,
MeteringConsumerService,
MeteringEventsManager,
MeteringEventsRepository,
Expand All @@ -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({
Expand All @@ -40,6 +46,10 @@ import { StatsDProvider } from '@entitlements/shared/metrics/statsd';
MeteringEventsRepository,
MeteringPubSubClientProvider,
MeteringRedisClientProvider,
ClickHouseMetrics,
ConsumerMetrics,
PrometheusRegistryProvider,
PrometheusServer,
StatsDProvider,
StrapiClient,
UsageCountersManager,
Expand Down
5 changes: 5 additions & 0 deletions apps/metering-subscriber/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -29,6 +30,10 @@ export class RootConfig {
@IsDefined()
public readonly statsDConfig!: Partial<StatsDConfig>;

@Type(() => PrometheusConfig)
@ValidateNested()
public readonly prometheusConfig: PrometheusConfig = new PrometheusConfig();

@Type(() => SentryConfig)
@ValidateNested()
@IsDefined()
Expand Down
18 changes: 18 additions & 0 deletions apps/metering-sweep/src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { SentryGlobalFilter, SentryModule } from '@sentry/nestjs/setup';

import {
ClickHouseClient,
ClickHouseMetrics,
ClickHouseRateLimitersProvider,
MeteringFirestoreProvider,
MeteringLockRedisClientProvider,
Expand All @@ -20,18 +21,27 @@ import {
MeteringSweepRepository,
MeteringSweepService,
MeteringWebhookManager,
RefillMetrics,
SchedulerMetrics,
SweepMetrics,
UsageCountersManager,
UsageGrantsManager,
UsageGrantsMetrics,
UsageRefillManager,
UsageRefillRepository,
UsageRefillService,
WebhookMetrics,
} from '@entitlements/metering';
import {
MeteringConfigurationManager,
StrapiClient,
} 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,
Expand Down Expand Up @@ -71,6 +81,14 @@ import { AppService } from './app.service';
MeteringSweepRepository,
MeteringSweepService,
MeteringWebhookManager,
ClickHouseMetrics,
RefillMetrics,
SchedulerMetrics,
SweepMetrics,
UsageGrantsMetrics,
WebhookMetrics,
PrometheusRegistryProvider,
PrometheusServer,
StatsDProvider,
StrapiClient,
UsageCountersManager,
Expand Down
5 changes: 5 additions & 0 deletions apps/metering-sweep/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';

Expand All @@ -32,6 +33,10 @@ export class RootConfig {
@IsDefined()
public readonly statsDConfig!: Partial<StatsDConfig>;

@Type(() => PrometheusConfig)
@ValidateNested()
public readonly prometheusConfig: PrometheusConfig = new PrometheusConfig();

@Type(() => SentryConfig)
@ValidateNested()
@IsDefined()
Expand Down
3 changes: 3 additions & 0 deletions dev.env
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions docker-compose-development.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ services:
PORT: 3037
ports:
- '3037:3037'
- '9464:9464'
healthcheck:
test:
[
Expand Down Expand Up @@ -54,6 +55,7 @@ services:
PORT: 3038
ports:
- '3038:3038'
- '9465:9464'
depends_on:
api:
condition: service_healthy
Expand All @@ -67,6 +69,7 @@ services:
PORT: 3039
ports:
- '3039:3039'
- '9466:9464'
depends_on:
clickhouse-migrate:
condition: service_completed_successfully
Expand All @@ -82,6 +85,7 @@ services:
PORT: 3040
ports:
- '3040:3040'
- '9467:9464'
depends_on:
clickhouse-migrate:
condition: service_completed_successfully
Expand Down
9 changes: 9 additions & 0 deletions libs/metering/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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';
Expand All @@ -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';
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -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';
Expand Down Expand Up @@ -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,
Expand Down
Loading