{"id":50931395,"url":"https://github.com/ianmurrays/meter_box","last_synced_at":"2026-06-17T04:32:18.385Z","repository":{"id":357118672,"uuid":"1234423761","full_name":"ianmurrays/meter_box","owner":"ianmurrays","description":null,"archived":false,"fork":false,"pushed_at":"2026-05-10T12:33:47.000Z","size":338,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2026-05-11T13:02:54.466Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"Ruby","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/ianmurrays.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE.txt","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-05-10T06:57:14.000Z","updated_at":"2026-05-10T12:33:52.000Z","dependencies_parsed_at":null,"dependency_job_id":"11705586-ccb9-4838-97d0-88113c38c295","html_url":"https://github.com/ianmurrays/meter_box","commit_stats":null,"previous_names":["ianmurrays/meter_box"],"tags_count":1,"template":false,"template_full_name":null,"purl":"pkg:github/ianmurrays/meter_box","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ianmurrays%2Fmeter_box","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ianmurrays%2Fmeter_box/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ianmurrays%2Fmeter_box/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ianmurrays%2Fmeter_box/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/ianmurrays","download_url":"https://codeload.github.com/ianmurrays/meter_box/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/ianmurrays%2Fmeter_box/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":34276689,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-26T15:22:16.424Z","status":"online","status_checked_at":"2026-06-13T02:00:06.617Z","response_time":62,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-06-17T04:32:17.522Z","updated_at":"2026-06-17T04:32:18.370Z","avatar_url":"https://github.com/ianmurrays.png","language":"Ruby","funding_links":[],"categories":[],"sub_categories":[],"readme":"# MeterBox\n\n[![Gem Version](https://badge.fury.io/rb/meter_box.svg)](https://badge.fury.io/rb/meter_box)\n[![Test](https://github.com/ianmurrays/meter_box/actions/workflows/test.yml/badge.svg)](https://github.com/ianmurrays/meter_box/actions/workflows/test.yml)\n\n\u003cp align=\"center\"\u003e\n  \u003cimg src=\"logo.png\" alt=\"MeterBox\" width=\"400\"\u003e\n\u003c/p\u003e\n\n\u003e **Note**: MeterBox is not production-ready. Use at your own risk.\n\nAppend-only, multi-dimensional usage metering for ActiveRecord and PostgreSQL.\n\nMeterBox records usage events against polymorphic owners with typed dimensions, then queries them with time-range filtering and dimension breakdowns. Events are immutable — corrections are new events with negative values.\n\n## Requirements\n\n- Ruby \u003e= 3.2\n- ActiveRecord \u003e= 7.1\n- PostgreSQL (JSONB columns, GIN indexes, partial unique indexes)\n\n## Getting Started\n\nAdd the gem to your Gemfile:\n\n```ruby\ngem \"meter_box\"\n```\n\nRun the install generator:\n\n```bash\nbundle install\nrails generate meter_box:install\nrails db:migrate\n```\n\nThis creates:\n- A migration for the `meter_box_events` table\n- An initializer at `config/initializers/meter_box.rb`\n\n\u003e **PostgreSQL 17+**: The generated migration uses `gen_random_uuid()` for primary keys. If your database supports it, you can change this to `uuidv7()` for time-ordered UUIDs.\n\n## Configuration\n\nDeclare your meters in the initializer. Each meter has a name (a symbol), an optional aggregation type, and optional dimensions:\n\n```ruby\n# config/initializers/meter_box.rb\nMeterBox.configure do |config|\n  config.meter :signatures,\n    dimensions: {\n      method:        { values: %i[mitid otp], required: true },\n      subaccount_id: { required: false }\n    }\n\n  config.meter :api_calls,\n    aggregation: :count,\n    dimensions: {\n      endpoint: { required: true }\n    }\n\n  config.meter :temperature,\n    aggregation: :latest,\n    dimensions: {\n      sensor: { required: true, values: %i[indoor outdoor] }\n    }\nend\n```\n\n### Aggregation types\n\nThe `aggregation:` option controls how `MeterBox.total` and `MeterBox.breakdown` aggregate events. Defaults to `:sum`.\n\n| Type | SQL equivalent | Return type | Empty scope |\n|------|---------------|-------------|-------------|\n| `:sum` | `SUM(value)` | `Numeric` | `0` |\n| `:count` | `COUNT(*)` | `Integer` | `0` |\n| `:max` | `MAX(value)` | `Numeric` | `nil` |\n| `:min` | `MIN(value)` | `Numeric` | `nil` |\n| `:mean` | `AVG(value)` | `BigDecimal` | `nil` |\n| `:latest` | Value from the most recent event | `Numeric` | `nil` |\n| `:count_distinct` | `COUNT(DISTINCT value)` | `Integer` | `0` |\n\n`:latest` orders by `recorded_at DESC`, breaking ties with `created_at DESC`.\n\n**`:count` vs `:sum`**: When every event uses the default `value: 1`, `:count` and `:sum` return the same number. They diverge when events carry varying values — `:sum` adds up the `value` column while `:count` counts rows regardless of value. If you're counting occurrences (API calls, logins), `:sum` with the default value is sufficient. `:count` is useful when events carry a meaningful value (e.g., bytes transferred) but you still want to know how many events occurred.\n\n### Dimension options\n\n| Option | Type | Default | Description |\n|--------|------|---------|-------------|\n| `required` | Boolean | `false` | When `true`, `MeterBox.record` raises `MissingDimension` if this key is absent |\n| `values` | Array of symbols | _(none)_ | Constrains allowed values. Omit to allow any value. Symbols and strings are interchangeable |\n\n### Freeze semantics\n\n`MeterBox.configure` freezes the registry after the block returns. Any attempt to register a meter afterwards raises `ConfigurationFrozen`. This ensures meters are defined at boot time and version with your codebase.\n\n## Usage\n\nMeterBox exposes five public methods. All accept keyword arguments.\n\n### `MeterBox.record`\n\nRecords a usage event.\n\n```ruby\nMeterBox.record(\n  owner:           account,            # any ActiveRecord model (polymorphic)\n  meter:           :signatures,        # registered meter name\n  value:           1,                  # any Numeric (Integer, Float, BigDecimal), defaults to 1\n  dimensions:      { method: :mitid }, # validated against meter declaration\n  metadata:        { session: \"abc\" }, # free-form JSONB, never queried\n  idempotency_key: \"evt-123\",          # optional, prevents duplicate inserts\n  recorded_at:     Time.current        # defaults to now; backfill with past timestamps\n)\n# =\u003e MeterBox::Event\n```\n\n**Idempotency**: When an `idempotency_key` is provided, a second call with the same key (scoped to owner + meter) returns the original event without inserting a duplicate or raising an error.\n\n**Corrections**: To correct a previous event, record a new event with a negative `value`. MeterBox never updates or deletes rows.\n\n```ruby\nMeterBox.record(owner: account, meter: :signatures, value: -1,\n                dimensions: { method: :mitid },\n                metadata: { reason: \"double-emitted\" })\n```\n\n### `MeterBox.total`\n\nReturns the aggregated result for matching events, using the meter's configured aggregation type.\n\n```ruby\nMeterBox.total(\n  owner: account,\n  meter: :signatures,\n  since: Time.utc(2026, 1, 1),         # inclusive, optional\n  until: Time.utc(2026, 2, 1),         # exclusive, optional\n  where: { method: :mitid }            # dimension filter, optional\n)\n# =\u003e Numeric or nil (see aggregation types table)\n```\n\n- `since` is **inclusive** (`recorded_at \u003e= since`)\n- `until` is **exclusive** (`recorded_at \u003c until`)\n- Return value depends on aggregation type — `:sum` and `:count` return `0` for empty scopes; `:max`, `:min`, `:mean`, and `:latest` return `nil`\n\n### `MeterBox.breakdown`\n\nGroups aggregated results by one or more dimensions.\n\n```ruby\nMeterBox.breakdown(\n  owner: account,\n  meter: :signatures,\n  by:    :method,                       # symbol or array of symbols\n  since: Time.utc(2026, 1, 1),\n  until: Time.utc(2026, 2, 1)\n)\n# =\u003e { { method: \"mitid\" } =\u003e 42, { method: \"otp\" } =\u003e 17 }\n```\n\nReturns an empty hash when no events match. The `by:` keys must be declared dimensions on the meter.\n\n### `MeterBox.over_cap?`\n\nChecks whether the total meets or exceeds a given cap.\n\n```ruby\nMeterBox.over_cap?(\n  owner: account,\n  meter: :signatures,\n  cap:   1000,\n  since: Time.utc(2026, 1, 1),\n  where: { method: :mitid }\n)\n# =\u003e true / false\n```\n\nMeterBox does not store cap values — the caller supplies the cap. This keeps plan/billing logic in the host application.\n\n### `MeterBox.events_for`\n\nReturns an `ActiveRecord::Relation` of matching events for drill-down queries.\n\n```ruby\nevents = MeterBox.events_for(\n  owner: account,\n  meter: :signatures,\n  since: 1.month.ago,\n  where: { method: :mitid }\n)\n\nevents.find_each do |event|\n  puts \"#{event.recorded_at}: #{event.value} (#{event.dimensions})\"\nend\n```\n\n## Errors\n\nAll errors inherit from `MeterBox::Error \u003c StandardError`.\n\n| Error | Raised when |\n|-------|-------------|\n| `ConfigurationFrozen` | Registering a meter after `configure` has run |\n| `UnknownMeter` | Recording or querying with an unregistered meter name |\n| `MissingDimension` | A required dimension is absent on `record` |\n| `UnknownDimension` | An undeclared dimension key is used on `record`, `where:`, or `by:` |\n| `InvalidDimensionValue` | A dimension value is not in the declared `values:` list |\n| `MissingOwner` | `owner` is `nil` or has a `nil` id |\n| `InvalidValue` | `value` is not Numeric, or `metadata` is not a Hash |\n\n## Database Schema\n\nMeterBox uses a single table: `meter_box_events`.\n\n| Column | Type | Notes |\n|--------|------|-------|\n| `id` | UUID | Primary key |\n| `owner_type` | string | Polymorphic type |\n| `owner_id` | string | Stored as string to support any PK type |\n| `meter_name` | string | Registered meter name |\n| `value` | decimal | Signed; supports integers and fractional values; negative for corrections |\n| `dimensions` | JSONB | Validated, aggregation-relevant tags |\n| `metadata` | JSONB | Free-form audit context, never queried |\n| `idempotency_key` | string | Nullable; scoped unique per owner+meter |\n| `recorded_at` | datetime | Business time (can be backfilled) |\n| `created_at` | datetime | Insert time |\n\nThree indexes:\n- **Composite** on `(owner_type, owner_id, meter_name, recorded_at)` for query performance\n- **GIN** on `dimensions` for JSONB queries\n- **Partial unique** on `(owner_type, owner_id, meter_name, idempotency_key)` where `idempotency_key IS NOT NULL`\n\n## MeterBox vs usage_credits\n\n[usage_credits](https://github.com/rameerez/usage_credits) is a credits-based billing system. MeterBox is a metering primitive. They solve different problems and can work together.\n\n| | MeterBox | usage_credits |\n|---|---|---|\n| **Purpose** | Record and query raw usage events | Manage a credits wallet with spending, fulfillment, and billing |\n| **Data model** | Single append-only events table | Multi-table ledger (wallets, transactions, allocations, fulfillments) |\n| **What it tracks** | Dimensioned event counts/sums | Credit balance with FIFO allocation and expiration |\n| **Billing integration** | None — metering only | Stripe/PayPal via the `pay` gem |\n| **Dimensions** | Typed, validated, queryable (`by:`, `where:`) | No built-in dimension system |\n| **Aggregation** | `total`, `breakdown`, time-range filters | Transaction history queries |\n| **Idempotency** | Built-in via `idempotency_key` | Via `pay` gem for charges |\n| **Database** | PostgreSQL (JSONB, GIN indexes) | Any ActiveRecord-supported database |\n| **Corrections** | Negative-value events | Refunds and adjustments |\n| **Scope** | ~300 LOC, zero billing opinions | Full billing stack with subscriptions, packs, webhooks |\n\n**When to use MeterBox**: You need a metering layer that records what happened — how many signatures, API calls, or documents were processed — and you want to query that data with dimensional breakdowns and time ranges. Billing decisions (plans, caps, invoicing) live in your application code.\n\n**When to use usage_credits**: You want a turnkey credits system with wallets, spending, subscriptions, credit packs, and Stripe integration out of the box.\n\n**Using both**: MeterBox records the raw events; your application reads the totals to decide when to deduct credits via usage_credits.\n\n## Testing Your Application\n\nIn your test suite, reset the MeterBox configuration in setup/teardown to avoid state leakage:\n\n```ruby\nclass MyTest \u003c ActiveSupport::TestCase\n  setup do\n    MeterBox.reset!\n    MeterBox.configure do |config|\n      config.meter :signatures,\n        dimensions: { method: { required: true, values: %i[mitid otp] } }\n    end\n  end\n\n  teardown do\n    MeterBox.reset!\n  end\nend\n```\n\n## Development\n\nPrerequisites: Docker (for PostgreSQL).\n\n```bash\ngit clone https://github.com/ianmurrays/meter_box.git\ncd meter_box\ndocker compose up -d --wait\nbundle install\nbundle exec rake test\n```\n\nTo stop the database:\n\n```bash\ndocker compose down\n```\n\n## License\n\nMIT License. See [LICENSE.txt](LICENSE.txt).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fianmurrays%2Fmeter_box","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fianmurrays%2Fmeter_box","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fianmurrays%2Fmeter_box/lists"}