Package Exports
- @contractspec/lib.metering
- @contractspec/lib.metering/aggregation
- @contractspec/lib.metering/aggregation/index
- @contractspec/lib.metering/analytics/posthog-metering
- @contractspec/lib.metering/analytics/posthog-metering-reader
- @contractspec/lib.metering/contracts
- @contractspec/lib.metering/contracts/index
- @contractspec/lib.metering/docs
- @contractspec/lib.metering/docs/index
- @contractspec/lib.metering/docs/metering.docblock
- @contractspec/lib.metering/entities
- @contractspec/lib.metering/entities/index
- @contractspec/lib.metering/events
- @contractspec/lib.metering/metering.capability
- @contractspec/lib.metering/metering.feature
Readme
@contractspec/lib.metering
Website: https://contractspec.io/
Usage metering and billing core module for ContractSpec applications.
Overview
This module provides a reusable metering system that can be used to track usage-based metrics across all ContractSpec applications. It supports:
- Metric Definitions: Define what metrics to track
- Usage Recording: Record usage events
- Aggregation: Roll up usage into summaries
- Thresholds & Alerts: Monitor usage against limits
- Billing Integration: Connect usage to billing/plans
Entities
MetricDefinition
Defines a trackable metric.
| Field | Type | Description |
|---|---|---|
| id | string | Unique identifier |
| key | string | Metric key (e.g., api_calls, storage_gb) |
| name | string | Human-readable name |
| description | string | Metric description |
| unit | string | Unit of measurement |
| aggregationType | enum | How to aggregate (count, sum, avg, max, min) |
| resetPeriod | enum | When to reset (never, hourly, daily, monthly) |
| orgId | string | Organization scope (null = global) |
UsageRecord
Individual usage event.
| Field | Type | Description |
|---|---|---|
| id | string | Unique identifier |
| metricKey | string | Metric being recorded |
| subjectType | string | Subject type (org, user, project) |
| subjectId | string | Subject identifier |
| quantity | decimal | Usage quantity |
| timestamp | datetime | When usage occurred |
| metadata | json | Additional context |
UsageSummary
Pre-aggregated usage summary.
| Field | Type | Description |
|---|---|---|
| id | string | Unique identifier |
| metricKey | string | Metric key |
| subjectType | string | Subject type |
| subjectId | string | Subject identifier |
| periodType | enum | Period type (hourly, daily, monthly) |
| periodStart | datetime | Period start time |
| periodEnd | datetime | Period end time |
| totalQuantity | decimal | Aggregated quantity |
| recordCount | int | Number of records aggregated |
UsageThreshold
Threshold configuration for alerts.
| Field | Type | Description |
|---|---|---|
| id | string | Unique identifier |
| metricKey | string | Metric to monitor |
| subjectType | string | Subject type |
| subjectId | string | Subject identifier |
| threshold | decimal | Threshold value |
| action | enum | Action when exceeded (alert, block, none) |
| notifyEmails | json | Email addresses to notify |
Contracts
Commands
metric.define- Define a new metricmetric.update- Update metric definitionmetric.delete- Delete a metricusage.record- Record a usage eventusage.recordBatch- Record multiple usage eventsthreshold.create- Create a usage thresholdthreshold.update- Update a thresholdthreshold.delete- Delete a threshold
Queries
metric.get- Get metric definitionmetric.list- List all metricsusage.get- Get usage for a subjectusage.getSummary- Get aggregated usage summaryusage.export- Export usage datathreshold.list- List thresholds
Events
metric.defined- Metric was definedusage.recorded- Usage was recordedusage.aggregated- Usage was aggregated into summarythreshold.exceeded- Usage exceeded a thresholdthreshold.approaching- Usage approaching threshold (80%)
Usage
import {
MetricDefinitionEntity,
RecordUsageContract,
UsageAggregator
} from '@contractspec/lib.metering';
// Define a metric
await meteringService.defineMetric({
key: 'api_calls',
name: 'API Calls',
unit: 'calls',
aggregationType: 'COUNT',
resetPeriod: 'MONTHLY',
});
// Record usage
await meteringService.recordUsage({
metricKey: 'api_calls',
subjectType: 'org',
subjectId: 'org-123',
quantity: 1,
});
// Get usage summary
const summary = await meteringService.getUsageSummary({
metricKey: 'api_calls',
subjectType: 'org',
subjectId: 'org-123',
periodType: 'MONTHLY',
periodStart: new Date('2024-01-01'),
});Aggregation
The module includes an aggregation engine that periodically rolls up usage records:
import { UsageAggregator } from '@contractspec/lib.metering/aggregation';
const aggregator = new UsageAggregator({
storage: usageStorage,
});
// Run hourly aggregation
await aggregator.aggregate({
periodType: 'HOURLY',
periodStart: new Date(),
});Integration
This module integrates with:
@contractspec/lib.jobs- Scheduled aggregation jobs@contractspec/module.notifications- Threshold alerts@contractspec/lib.identity-rbac- Subject resolution
Schema Contribution
import { meteringSchemaContribution } from '@contractspec/lib.metering';
export const schemaComposition = {
modules: [
meteringSchemaContribution,
// ... other modules
],
};