# API: hyper-p2p-histogram-gossip **Export:** `{ HyperP2PHistogramGossip, PROTOCOL }` **Protocol:** `histogram-gossip/v1` ## Overview `HyperP2PHistogramGossip` maintains per-metric fixed-bucket histograms locally and merges remote bucket snapshots from peers. Each `observe` updates min/max, increments bucket counts, and gossips `histogram-buckets` for swarm-wide percentile estimates. ## Constructor ```js const { HyperP2PHistogramGossip } = require('hyper-p2p-histogram-gossip') const hist = new HyperP2PHistogramGossip(opts) ``` | Option | Type | Default | Description | |--------|------|---------|-------------| | `topic` | `string` \| `Buffer` \| `null` | `null` | Swarm topic | | `keyPair` | `KeyPair` | new key pair | `peerHex` on gossip | | `buckets` | `number` | `10` | Bucket count per metric | ## Methods ### `observe(metric, value)` - `metric` non-empty string; `value` finite number - Updates histogram, emits `observe` - Gossips: ```js { type: 'histogram-buckets', metric, min, max, counts: [...], peer, at } ``` ### `percentile(metric, p)` - `p` clamped 0–100 - Estimates percentile from merged bucket counts - **Returns:** `null` if no observations ### `snapshot(metric)` Returns `{ metric, min, max, counts, total }` or `null`. ### `metrics()` Sorted metric names. ### `getStats()` ```js { observed, gossipIn, gossipOut, metrics, protocol } ``` ### `ready()` / `close()` Standard `initModuleSwarm` lifecycle. ## Merge logic `_mergeBuckets` - Expands min/max to include remote - Adds bucket counts element-wise - Adds remote total from sum of remote counts ## Events | Event | Payload | |-------|---------| | `observe` | `{ metric, value }` | | `remote-buckets` | `{ metric, peer }` | | `closed` | — | ## Wire messages | type | fields | |------|--------| | `histogram-buckets` | `metric`, `min`, `max`, `counts`, `peer`, `at` | ## Bucket indexing When `min === max`, all mass goes to bucket 0. Otherwise linear bins across `[min, max]`. ## Testing ```bash npm install && npm test ```