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: Explicit overlay neighbor graph with max degree and churn healing.
<!-- 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-overlay-topology
Production network stack module: Hyperswarm discovery + Protomux when `topic` is set.
**Category:** Network stack
**Composes with:** `hyper-p2p-protocol-handshake`, `hyper-p2p-connection-pool`
**Protocol:** `overlay-topology/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 { HyperP2POverlayTopology } = require('hyper-p2p-overlay-topology')
const topic = process.argv[2] // 64-char hex or string
const mod = new HyperP2POverlayTopology({ 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/) — `overlay-topology-two-node.js`
## Test
```bash
npm install && npm test
```
@@ -0,0 +1,91 @@
# API: hyper-p2p-overlay-topology
**Protocol:** `overlay-topology/v1`
**Export:** `HyperP2POverlayTopology`
## Overview
Production network stack module: Hyperswarm discovery + Protomux when `topic` is set.
## Constructor
```js
const mod = new HyperP2POverlayTopology(opts)
```
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `topic` | varies | null | topic |
| `keyPair` | KeyPair | random Ed25519 | keyPair |
## Methods
### `addNeighbor(peerId, weight = 1)`
- **Returns:** `value`
- **Throws:**
- `Error: maxDegree exceeded`
- `Error: peerId required`
- `Error: weight must be non-negative`
### `removeNeighbor(peerId)`
- **Returns:** `value`
- **Throws:**
- `Error: peerId required`
### `getNeighbors(—)`
- **Returns:** `value`
- **Throws:** — (none documented in method body)
### `suggestReplacement(failedPeer)`
- **Returns:** `value`
- **Throws:**
- `Error: failedPeer required`
### `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 |
| `neighbor-added` | n |
| `neighbor-removed` | payload object |
## 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 `overlay-topology/v1`.
## Testing
```bash
npm install && npm test
```
Integration: [`../../real_tests/integration/overlay-topology-two-node.js`](../../../real_tests/integration/overlay-topology-two-node.js)
@@ -0,0 +1,46 @@
# Architecture: hyper-p2p-overlay-topology
**Category:** Network stack
```mermaid
flowchart LR
App[Application] --> Mod[HyperP2POverlayTopology]
Mod --> Mux[Protomux overlay-topology/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 |
|------|--------|-----------|----------|
| `topology-remove` | peerId | gossip | Handled in onmessage / gossipSend |
| `topology-update` | peerId, neighbors[] | 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`.
See [`../_shared/WAVE6_NETWORK_STACK.md`](../../_shared/WAVE6_NETWORK_STACK.md) for layer ordering.
@@ -0,0 +1,11 @@
require('bare-process/global')
const { HyperP2POverlayTopology } = require('..')
async function main () {
const m = new HyperP2POverlayTopology()
m.addNeighbor('relay-1')
console.log('ok', m.getStats())
await m.close()
}
main().catch(console.error)
@@ -0,0 +1,82 @@
require('bare-process/global')
const EventEmitter = require('bare-events')
const b4a = require('b4a')
const { initModuleSwarm, gossipSend } = require('../../_shared/p2p-bare.js')
const PROTOCOL = 'overlay-topology/v1'
class HyperP2POverlayTopology extends EventEmitter {
constructor (opts = {}) {
super()
this.topic = opts.topic || null
this.keyPair = opts.keyPair || require('hypercore-crypto').keyPair()
this.peerId = b4a.toString(this.keyPair.publicKey, 'hex')
this.maxDegree = opts.maxDegree != null ? opts.maxDegree : 8
this._neighbors = new Map()
this._stats = { added: 0, removed: 0, healed: 0 }
this.swarm = null
this._peerMsgs = null
}
addNeighbor (peerId, weight = 1) {
if (!peerId || typeof peerId !== 'string') throw new Error('peerId required')
if (weight < 0) throw new Error('weight must be non-negative')
if (this._neighbors.size >= this.maxDegree && !this._neighbors.has(peerId)) {
throw new Error('maxDegree exceeded')
}
const n = { peerId, weight, at: Date.now() }
this._neighbors.set(peerId, n)
this._stats.added++
if (this._peerMsgs) gossipSend(this, { type: 'topology-update', neighbor: n })
this.emit('neighbor-added', n)
return n
}
removeNeighbor (peerId) {
if (!peerId) throw new Error('peerId required')
const ok = this._neighbors.delete(peerId)
if (ok) {
this._stats.removed++
if (this._peerMsgs) gossipSend(this, { type: 'topology-remove', peerId })
this.emit('neighbor-removed', { peerId })
}
return ok
}
getNeighbors () {
return [...this._neighbors.values()]
}
suggestReplacement (failedPeer) {
if (!failedPeer) throw new Error('failedPeer required')
let best = null
for (const n of this._neighbors.values()) {
if (n.peerId === failedPeer) continue
if (!best || n.weight < best.weight) best = n
}
if (best) this._stats.healed++
return best
}
getStats () { return { ...this._stats, degree: this._neighbors.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 === 'topology-update' && data.neighbor) {
if (this._neighbors.size < this.maxDegree) this._neighbors.set(data.neighbor.peerId, data.neighbor)
} else if (data?.type === 'topology-remove') this._neighbors.delete(data.peerId)
}
})
return this
}
async close () {
if (this.swarm) await this.swarm.destroy().catch(() => {})
this.swarm = null
this._neighbors.clear()
this.emit('closed')
}
}
module.exports = { HyperP2POverlayTopology, PROTOCOL }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,25 @@
{
"name": "hyper-p2p-overlay-topology",
"version": "0.3.1",
"description": "Explicit overlay neighbor graph with max degree and churn healing.",
"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 { HyperP2POverlayTopology } = require('../index.js')
test('hyper-p2p-overlay-topology: basic operation', async (t) => {
const m = new HyperP2POverlayTopology()
m.addNeighbor('peer-a', 1)
t.is(m.getNeighbors().length, 1)
await m.close()
})
test('hyper-p2p-overlay-topology: validation', async (t) => {
const m = new HyperP2POverlayTopology()
try {
m.addNeighbor(null)
t.fail('expected throw')
} catch (e) {
t.ok(e instanceof Error)
}
await m.close()
})
test('hyper-p2p-overlay-topology: getStats', async (t) => {
const m = new HyperP2POverlayTopology()
const s = m.getStats()
t.ok(s)
await m.close()
})
test('hyper-p2p-overlay-topology: close idempotent', async (t) => {
const m = new HyperP2POverlayTopology()
await m.close()
await m.close()
t.pass()
})