2.0 KiB
2.0 KiB
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
const { HyperP2PSlaBudget } = require('hyper-p2p-sla-budget')
const budget = new HyperP2PSlaBudget()
No options. Internal _services: Map<service, { remaining, total }>.
Methods
allocate(service, tokens)
servicenon-empty;tokensnon-negative finite number- Adds to
remainingandtotal - Returns: new
remainingbalance - Emits:
allocate{ service, tokens, remaining } - Increments:
stats.allocated
consume(service, n)
- Default
n = 1, non-negative - Returns:
trueif debited;falseif insufficient - Emits:
consumeorreject - Increments:
stats.consumedorstats.rejected
remaining(service)
Current balance or 0.
services()
Sorted service names.
snapshot(service)
{ service, remaining, total, used }
where used = total - remaining, or null.
reset(service)
Deletes one service or all if service omitted.
getStats()
{ 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
budget.allocate('api-read', 1000)
if (!budget.consume('api-read')) throw new Error('SLA budget exhausted')
Errors
assertNonEmpty(service); invalid token amounts throw.
Testing
npm install && npm test