Metadata-Version: 2.4
Name: nuclia-metering
Version: 0.1.0
Summary: Client library and Protobuf contract to send usage events to the Nuclia usage pipeline
Author: Bosutech XXI S.L.
License-Expression: Apache-2.0
License-File: LICENSE.txt
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: AsyncIO
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Programming Language :: Python :: 3.14
Classifier: Programming Language :: Python :: 3.15
Classifier: Typing :: Typed
Project-URL: Repository, https://github.com/nuclia/nuclia-metering
Project-URL: Changelog, https://github.com/nuclia/nuclia-metering/blob/main/CHANGELOG.md
Requires-Python: >=3.12
Requires-Dist: nats-py<3,>=2.10.0
Requires-Dist: protobuf<8,>=7.35.1
Description-Content-Type: text/markdown

# nuclia-metering

Client library and Protobuf contract (`usage.v1`) used by emitting services to send usage to the Nuclia usage pipeline.

- Validates events where they are created, with a stable idempotency key and a frozen UTC timestamp.
- Publishes them to the zone's `usage-events` JetStream stream and only treats them as sent once acknowledged.
- Retries inside the stream's duplicate window, buffers events during short outages, and exposes metrics hooks.
- Services send raw values only (bytes, seconds, requests…), never prices or credits.

## Install

```sh
pip install nuclia-metering
# or
uv add nuclia-metering
```

Requires Python 3.12+.

## Quick start

```python
import asyncio

from nuclia_metering import UsageClient, UsageClientConfig


async def main() -> None:
    config = UsageClientConfig(service="nucliadb")
    async with UsageClient(config=config, servers="nats://localhost:4222") as client:
        await client.emit(
            entity_id="kb-123",
            meter_slug="nucliadb.search.requests",
            value=1,
            properties={"entity_type": "kb"},
        )


asyncio.run(main())
```

Read the [integration guide](docs/integration-guide.md) before sending usage from a new service, and see
[examples/simple_service](examples/simple_service) for a runnable example.

Library API arguments are keyword-only: use `UsageClient(config=config)` and
`client.emit(entity_id="kb-123", meter_slug="nucliadb.search.requests", value=1)`.
Positional arguments raise `TypeError`, preventing accidental argument-order mistakes.

## Contract

The Protobuf definitions live in [proto/usage/v1/usage.proto](proto/usage/v1/usage.proto). The Python
modules are generated when the package is built and ship as `nuclia_metering.proto.usage.v1.usage_pb2`.

Properties allow at most **8 keys**, each at most **32 UTF-8 bytes**, with values at most **64 UTF-8 bytes**.
Events are validated automatically when created. The regional usage consumer applies the same validation,
defined in `nuclia_metering.validation`.

`USAGE_KEY_NAMESPACE` is `1334a099-f030-4232-bbd6-b958cba95ebd`. A business idempotency key is sent as
`UUIDv5(USAGE_KEY_NAMESPACE, key)`, so every language derives the same id.

## Development

### Prerequisites

uv installs Python 3.12+ and every Python tool (ruff, ty, pytest, protoc via `grpcio-tools`). The other tools are
only needed for some tasks:

| Tool | Needed for | Install |
|------|------------|---------|
| [uv](https://docs.astral.sh/uv/) | everything | [Installing uv](https://docs.astral.sh/uv/getting-started/installation/) |
| [buf](https://buf.build/docs/) | changing `.proto` files | [Install the Buf CLI](https://buf.build/docs/cli/installation/) |
| [Docker](https://www.docker.com/) (or [Rancher Desktop](https://rancherdesktop.io/)) | integration tests, the TruffleHog pre-commit hook and the [example service](examples/simple_service) | [Get Docker](https://docs.docker.com/get-started/get-docker/) or [Install Rancher Desktop](https://docs.rancherdesktop.io/getting-started/installation/) |

CI runs all of these checks, so a missing optional tool only means you find out on the PR.

### Commands

Run `make` to list every target.

```sh
make install           # uv sync (generates the protobuf modules into src/) and pre-commit hooks
make proto             # regenerate the protobuf modules after changing a .proto file
make format            # ruff format/fix and buf format
make lint              # ruff, ty, buf lint and buf format check
make breaking          # buf breaking against main
make test              # all tests; also test-unit and test-integration
make check             # definition of done: lint, buf breaking and all tests
make api-snapshot      # regenerate tests/snapshots/public_api.txt after an intended public API change
make pre-commit        # every pre-commit hook on the whole repo
make build             # sdist and wheel into dist/
make example           # run the example service (NATS_PORT=14222 if 4222 is taken); make example-down to stop
```

The pre-commit hooks block direct commits to `main` and run TruffleHog on staged changes to catch leaked secrets.

### Security scanning

Every repository in a production workload must run these scans. They use organization-level secrets, so they only run
in GitHub Actions:

| Workflow | Tool | Runs on |
|----------|------|---------|
| [trufflehog.yml](.github/workflows/trufflehog.yml) | TruffleHog secrets detection on the full history | every PR and push to `main` |
| [polaris.yml](.github/workflows/polaris.yml) | Polaris SAST (rapid on PRs, full on `main`) | PRs to and pushes to `main` |
| [bd_sca_scanner.yml](.github/workflows/bd_sca_scanner.yml) | Black Duck SCA of the runtime dependencies | changes to `uv.lock` or `pyproject.toml` |

If TruffleHog finds a secret, revoke and rotate it immediately. Removing it from the code is not enough.

Integration tests start NATS (`nats:2.15-alpine`, override with `NATS_IMAGE`) with
[testcontainers](https://testcontainers-python.readthedocs.io/); they are skipped when Docker is not available. With
Rancher Desktop or Colima, set `DOCKER_HOST` if `/var/run/docker.sock` does not exist.

### Working with AI agents

This repo is set up for GitHub Copilot (VS Code, CLI and code review). Agents and humans follow the same
contract in [AGENTS.md](AGENTS.md), and run `make check` before finishing. Procedures for common changes live in
[.github/skills](.github/skills). The one-time admin setup is in [docs/ai-setup.md](docs/ai-setup.md).

## Releasing

Releases are cut by release-please from [Conventional Commits](https://www.conventionalcommits.org/) and published to
PyPI with trusted publishing. Each release attests build provenance and a CycloneDX SBOM of the runtime dependencies
for the wheel and sdist. To verify a downloaded artifact:

```sh
gh attestation verify nuclia_metering-<version>-py3-none-any.whl --repo nuclia/nuclia-metering
gh attestation verify nuclia_metering-<version>-py3-none-any.whl --repo nuclia/nuclia-metering \
  --predicate-type https://cyclonedx.org/bom
```

On every push to `main`, release-please opens or updates a release PR with the next version, the changelog and the
version bumps in `pyproject.toml`, `uv.lock` and `.release-please-manifest.json`. Merging it tags the release and
publishes the package. Never edit the version by hand.

The commit type decides the next version. Use it in the PR title when squash-merging:

| Commit | Example | Release |
|--------|---------|---------|
| `fix:`, `perf:`, `revert:`, `deps:` | `fix: retry on ServerError responses` | patch (1.2.0 → 1.2.1) |
| `feat:` | `feat: add MAX meter helper` | minor (1.2.0 → 1.3.0) |
| `!` or `BREAKING CHANGE:` footer | `feat!: rename UsageClient.emit` | major (1.2.0 → 2.0.0)<br>minor before 1.0 (0.1.0 → 0.2.0) |
| `chore:`, `docs:`, `test:`, `ci:`, `refactor:`, `build:` | `docs: explain LAST meters` | no release |

To force a specific version (for example the first stable release), add a `Release-As: 1.0.0` footer to the commit
message.

Any change to `proto/usage/v1` that `buf breaking` rejects is a breaking change: add a new package version
(`usage.v2`) instead.
