This commit is contained in:
Raven Scott
2026-05-20 21:02:45 -04:00
parent 1f3f4b24a2
commit 14d0980b4f
734 changed files with 682 additions and 746 deletions
@@ -0,0 +1,16 @@
# Changelog
<!-- legacy: v0.1.0 -->
- Initial release: Gossip RTT/loss samples and recommended send rates.
<!-- legacy: v0.3.0 -->
- Wave 6: presence-tier API tables, architecture wire section, validation test.
<!-- legacy: v0.3.1 -->
- Wave 7: correct protocol in docs, getStats(), wire tables, category README.
## [0.3.2] - 2026-05-21
### Changed
- Exhaustive documentation pass (api, architecture, README) per DOC_STANDARDS.md.
@@ -0,0 +1,43 @@
# hyper-p2p-congestion-signal
Production network stack module: Hyperswarm discovery + Protomux when `topic` is set.
**Category:** Network stack
**Composes with:** `hyper-p2p-protocol-handshake`, `hyper-p2p-connection-pool`, `hyper-p2p-overlay-topology`
**Protocol:** `congestion-signal/v1`
## When to use
Multi-peer apps that need network stack over a shared Hyperswarm topic.
## When not to use
Single-process tools with no P2P topic (use local APIs only or skip `ready()`).
## Quick start
```js
const { HyperP2PCongestionSignal } = require('hyper-p2p-congestion-signal')
const topic = process.argv[2] // 64-char hex or string
const mod = new HyperP2PCongestionSignal({ topic, enableBackgroundTimers: false })
await mod.ready() // joins swarm when topic set
// ... application logic ...
await mod.close()
```
## Docs
- [docs/api.md](docs/api.md) — constructor, methods, events, errors
- [docs/architecture.md](docs/architecture.md) — wire types, state, composition
- [../_shared/PRODUCTION.md](../../_shared/PRODUCTION.md) — production checklist
- [../_shared/DOC_STANDARDS.md](../../_shared/DOC_STANDARDS.md) — documentation standards
- Integration: [`../../real_tests/integration/`](../../../real_tests/integration/) — `congestion-signal-two-node.js`
## Test
```bash
npm install && npm test
```
@@ -0,0 +1,83 @@
# API: hyper-p2p-congestion-signal
**Protocol:** `congestion-signal/v1`
**Export:** `HyperP2PCongestionSignal`
## Overview
Production network stack module: Hyperswarm discovery + Protomux when `topic` is set.
## Constructor
```js
const mod = new HyperP2PCongestionSignal(opts)
```
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `topic` | varies | null | topic |
| `keyPair` | KeyPair | random Ed25519 | keyPair |
| `baseRateBps` | number | 1_000_000 | baseRateBps |
## Methods
### `reportSample(peerId, rttMs, loss = 0)`
- **Returns:** `value`
- **Throws:**
- `Error: invalid rtt or loss`
- `Error: peerId required`
### `getHint(peerId)`
- **Returns:** `value`
- **Throws:** — (none documented in method body)
### `shouldThrottle(peerId)`
- **Returns:** `value`
- **Throws:** — (none documented in method body)
### `getStats(—)`
- **Returns:** `object`
- **Throws:** — (none documented in method body)
### `ready(—)`
- **Returns:** `Promise`
- **Throws:** — (none documented in method body)
### `close(—)`
- **Returns:** `Promise<void>`
- **Throws:** — (none documented in method body)
## Events
| Event | Payload |
|-------|---------|
| `closed` | no payload |
| `sample` | s |
## getStats()
Returns `{ ...this._stats }` — typically `ops`, `errors`, and module-specific counters (`created`, `relays`, `open`, `peers`, etc.).
Library-only modules may include `mode: 'local'`.
## Errors
Stable message substrings: see [`../_shared/ERROR_CODES.md`](../../_shared/ERROR_CODES.md).
## P2P
When `topic` is set, `ready()` joins Hyperswarm and opens Protomux `congestion-signal/v1`.
## Testing
```bash
npm install && npm test
```
Integration: [`../../real_tests/integration/congestion-signal-two-node.js`](../../../real_tests/integration/congestion-signal-two-node.js)
@@ -0,0 +1,45 @@
# Architecture: hyper-p2p-congestion-signal
**Category:** Network stack
```mermaid
flowchart LR
App[Application] --> Mod[HyperP2PCongestionSignal]
Mod --> Mux[Protomux congestion-signal/v1]
Mux --> Swarm[Hyperswarm]
```
## Sequence (P2P)
```mermaid
sequenceDiagram
participant App
participant Mod as Module
participant SW as Hyperswarm
participant Peer
App->>Mod: ready(topic)
Mod->>SW: join(topic)
SW->>Peer: connection
Mod->>Peer: gossip / Protomux
Peer-->>Mod: onmessage
Mod-->>App: emit(event)
```
## Wire messages
| type | fields | direction | behavior |
|------|--------|-----------|----------|
| `congestion-sample` | sample | gossip | Handled in onmessage / gossipSend |
## State model
- In-memory `Map` / `Set` structures for hot path
- Optional Hyperbee/Hypercore persistence when `storageDir` or `memoryOnly` is configured
- `close()` tears down swarm, timers, and clears ephemeral state
## Composition
Composes with: `hyper-p2p-protocol-handshake`, `hyper-p2p-connection-pool`, `hyper-p2p-overlay-topology`.
See [`../_shared/WAVE6_NETWORK_STACK.md`](../../_shared/WAVE6_NETWORK_STACK.md) for layer ordering.
@@ -0,0 +1,11 @@
require('bare-process/global')
const { HyperP2PCongestionSignal } = require('..')
async function main () {
const m = new HyperP2PCongestionSignal()
m.reportSample('peer', 30, 0)
console.log('ok', m.getStats())
await m.close()
}
main().catch(console.error)
@@ -0,0 +1,64 @@
require('bare-process/global')
const EventEmitter = require('bare-events')
const { initModuleSwarm, gossipSend } = require('../../_shared/p2p-bare.js')
const PROTOCOL = 'congestion-signal/v1'
class HyperP2PCongestionSignal extends EventEmitter {
constructor (opts = {}) {
super()
this.topic = opts.topic || null
this.keyPair = opts.keyPair || require('hypercore-crypto').keyPair()
this.baseRateBps = opts.baseRateBps || 1_000_000
this._samples = new Map()
this._stats = { samples: 0 }
this.swarm = null
this._peerMsgs = null
}
reportSample (peerId, rttMs, loss = 0) {
if (!peerId) throw new Error('peerId required')
if (rttMs < 0 || loss < 0 || loss > 1) throw new Error('invalid rtt or loss')
const s = { peerId, rttMs, loss, at: Date.now() }
this._samples.set(peerId, s)
this._stats.samples++
if (this._peerMsgs) gossipSend(this, { type: 'congestion-sample', sample: s })
this.emit('sample', s)
return s
}
getHint (peerId) {
const s = this._samples.get(peerId)
if (!s) return { sendRateBps: this.baseRateBps }
const factor = Math.max(0.1, 1 - s.loss - (s.rttMs / 1000) * 0.1)
return { sendRateBps: Math.floor(this.baseRateBps * factor), rttMs: s.rttMs, loss: s.loss }
}
shouldThrottle (peerId) {
const h = this.getHint(peerId)
return h.sendRateBps < this.baseRateBps * 0.5
}
getStats () { return { ...this._stats, peers: this._samples.size } }
async ready () {
if (this.swarm || !this.topic) return this
await initModuleSwarm(this, {
keyPair: this.keyPair, topic: this.topic, protocol: PROTOCOL,
onmessage: (data) => {
if (data?.type === 'congestion-sample' && data.sample) {
const cur = this._samples.get(data.sample.peerId)
if (!cur || data.sample.at >= cur.at) this._samples.set(data.sample.peerId, data.sample)
}
}
})
return this
}
async close () {
if (this.swarm) await this.swarm.destroy().catch(() => {})
this.swarm = null
this._samples.clear()
this.emit('closed')
}
}
module.exports = { HyperP2PCongestionSignal, PROTOCOL }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,25 @@
{
"name": "hyper-p2p-congestion-signal",
"version": "0.3.1",
"description": "Gossip RTT/loss samples and recommended send rates.",
"main": "index.js",
"type": "commonjs",
"license": "Apache-2.0",
"scripts": { "test": "brittle-bare test/test.js" },
"dependencies": {
"bare-events": "^2.8.0",
"bare-process": "^4.4.0",
"bare-timers": "^2.0.0",
"b4a": "^1.6.7",
"hypercore-crypto": "^3.0.0",
"protomux": "^3.0.0",
"compact-encoding": "^2.0.0"
},
"peerDependencies": { "hyperswarm": "^4.0.0", "bare": ">=1.0.0" },
"devDependencies": { "brittle": "^3.0.0" },
"imports": {
"process": { "bare": "bare-process", "default": "process" },
"events": { "bare": "bare-events", "default": "events" },
"timers": { "bare": "bare-timers", "default": "timers" }
}
}
@@ -0,0 +1,35 @@
require('bare-process/global')
const test = require('brittle')
const { HyperP2PCongestionSignal } = require('../index.js')
test('hyper-p2p-congestion-signal: basic operation', async (t) => {
const m = new HyperP2PCongestionSignal()
m.reportSample('p1', 50, 0.1)
t.ok(m.getHint('p1').sendRateBps > 0)
await m.close()
})
test('hyper-p2p-congestion-signal: validation', async (t) => {
const m = new HyperP2PCongestionSignal()
try {
m.reportSample(null, -1, 0)
t.fail('expected throw')
} catch (e) {
t.ok(e instanceof Error)
}
await m.close()
})
test('hyper-p2p-congestion-signal: getStats', async (t) => {
const m = new HyperP2PCongestionSignal()
const s = m.getStats()
t.ok(s)
await m.close()
})
test('hyper-p2p-congestion-signal: close idempotent', async (t) => {
const m = new HyperP2PCongestionSignal()
await m.close()
await m.close()
t.pass()
})