Files
modules/measurement-rate-control/hyper-p2p-sla-budget/docs/api.md
T
2026-05-20 23:36:32 -04:00

95 lines
2.0 KiB
Markdown

# API: hyper-p2p-sla-budget
**Export:** `{ HyperP2PSlaBudget, PROTOCOL }`
**Protocol:** `sla-budget/v1` (local-only)
## Overview
`HyperP2PSlaBudget` implements per-service token budgets: allocate capacity, consume tokens for work units, and reject when insufficient. Use to cap error budgets, API quota, or retry spend in SLA-aware Bare/Pear services.
## Constructor
```js
const { HyperP2PSlaBudget } = require('hyper-p2p-sla-budget')
const budget = new HyperP2PSlaBudget()
```
No options. Internal `_services: Map<service, { remaining, total }>`.
## Methods
### `allocate(service, tokens)`
- `service` non-empty; `tokens` non-negative finite number
- Adds to `remaining` and `total`
- **Returns:** new `remaining` balance
- **Emits:** `allocate` `{ service, tokens, remaining }`
- **Increments:** `stats.allocated`
### `consume(service, n)`
- Default `n = 1`, non-negative
- **Returns:** `true` if debited; `false` if insufficient
- **Emits:** `consume` or `reject`
- **Increments:** `stats.consumed` or `stats.rejected`
### `remaining(service)`
Current balance or `0`.
### `services()`
Sorted service names.
### `snapshot(service)`
```js
{ service, remaining, total, used }
```
where `used = total - remaining`, or `null`.
### `reset(service)`
Deletes one service or all if `service` omitted.
### `getStats()`
```js
{ allocated, consumed, rejected, services, protocol }
```
### `ready()` / `close()`
`close()` clears services, emits `closed`.
## Events
| Event | When | Payload |
|-------|------|---------|
| `allocate` | tokens added | `{ service, tokens, remaining }` |
| `consume` | successful debit | `{ service, n, remaining }` |
| `reject` | insufficient budget | `{ service, requested, remaining }` |
| `closed` | teardown | — |
## Wire messages
None.
## Usage pattern
```js
budget.allocate('api-read', 1000)
if (!budget.consume('api-read')) throw new Error('SLA budget exhausted')
```
## Errors
`assertNonEmpty(service)`; invalid token amounts throw.
## Testing
```bash
npm install && npm test
```