Add storage stack modules and track them in git

The modules workspace previously ignored every path matching `storage-*`,
which kept all Hypercore, Hyperbee, Hyperdrive, and Autobase packages out
of version control. Narrow .gitignore to test-artifact patterns only so
production category trees are committed.

Storage packages (23 total):
- storage-hypercore (7): replicator, seed-policy, fork-picker, merkle-sync,
  priority-fetch, bitfield-scheduler, audit-chain
- storage-hyperbee (5): batch-write, diff-follow, range-watch,
  secondary-index, tombstone-gc
- storage-hyperdrive (6): entry-catalog, gc-sweep, mirror-sync, mount-bridge,
  version-snapshot, watch-notify
- storage-autobase (5): fork-choice, view-sync, writer-lease, indexer-bus,
  light-writer

Implementation highlights:
- Shared attach/gossip helpers in _shared/storage-gossip-base.js
- P2P modules use Protomux gossip via p2p-bare; local planners omit swarm
- Recent deepen pass: priority queues, batch caps, audit export/import,
  watch/notify aliases on range-watch, fork/view lease helpers, etc.
- Per-package README, docs/api.md, docs/architecture.md, tests, examples

Also update modules/README.md doc hub links for the full storage stack
(hypercore, hyperbee, hyperdrive, autobase).

Co-authored-by: Cursor <[email protected]>
This commit is contained in:
Raven Scott
2026-05-21 00:17:51 -04:00
co-authored by Cursor
parent b10507b060
commit a11e22badc
214 changed files with 57132 additions and 5 deletions
+33
View File
@@ -0,0 +1,33 @@
# Storage (Autobase)
**Path:** `modules/storage-autobase/` · **Modules:** 5 (all production)
Doc hub: [`docs/storage-autobase/README.md`](../../docs/storage-autobase/README.md)
Autobase **coordination** for multi-writer logs: fork selection, view sync gossip, leases, indexer bus, and local write batching.
## Packages
| Module | Protocol | P2P |
|--------|----------|:---:|
| [hyper-p2p-autobase-fork-choice](./hyper-p2p-autobase-fork-choice/) | `autobase-fork-choice/v1` | yes |
| [hyper-p2p-autobase-view-sync](./hyper-p2p-autobase-view-sync/) | `autobase-view-sync/v1` | yes |
| [hyper-p2p-autobase-writer-lease](./hyper-p2p-autobase-writer-lease/) | `autobase-writer-lease/v1` | yes |
| [hyper-p2p-autobase-indexer-bus](./hyper-p2p-autobase-indexer-bus/) | `autobase-indexer-bus/v1` | yes |
| [hyper-p2p-autobase-light-writer](./hyper-p2p-autobase-light-writer/) | `autobase-light-writer/v1` | no |
## Composition
```text
fork-choice → pick canonical fork
view-sync → align version/hash across peers
writer-lease → gate who may append
light-writer → batch proposals → autobase.append
indexer-bus → fan-out index jobs after apply
```
## Test
```bash
cd hyper-p2p-autobase-fork-choice && npm test
```
@@ -0,0 +1,5 @@
# Changelog
## [0.0.0-scaffold]
- Registry scaffold: file tree, load smoke tests, docs stubs
@@ -0,0 +1,41 @@
# hyper-p2p-autobase-fork-choice
Registers Autobase view forks over gossip and picks the best by weight/version; align with `hyper-p2p-causal-consensus` for writer ordering. Hyperswarm gossip when `topic` is set.
**Category:** Storage (Autobase)
**Composes with:** `hyper-p2p-causal-consensus`
**Protocol:** `autobase-fork-choice/v1`
## When to use
Multiple Autobase views compete and peers must converge on one fork id.
## When not to use
Single linear Autobase with no fork hints.
## Quick start
```js
const { HyperP2PAutobaseForkChoice } = require('hyper-p2p-autobase-fork-choice')
const topic = process.argv[2] // 64-char hex or string
const mod = new HyperP2PAutobaseForkChoice({ topic })
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
## Test
```bash
npm install && npm test
```
@@ -0,0 +1,111 @@
# API: hyper-p2p-autobase-fork-choice
**Protocol:** `autobase-fork-choice/v1`
**Export:** `HyperP2PAutobaseForkChoice`
## Overview
Registers Autobase view forks over gossip and picks the best by weight/version; align with `hyper-p2p-causal-consensus` for writer ordering.
## Constructor
```js
const mod = new HyperP2PAutobaseForkChoice(opts)
```
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `topic` | string \| Buffer \| null | null | Hyperswarm topic; gossip attaches when set |
| `keyPair` | Ed25519 KeyPair | random | Signing identity for swarm |
| `autobase` | object \| null | null | Attached autobase instance (`attach()` also supported) |
## Methods
### `attach(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `registerView(…)`
- **Returns:** module-specific (see implementation)
- **Throws:**
- `Error: version must be non-negative`
### `pickBestFork(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `listViews(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `getStats(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `ready(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `close(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
## Events
| Event | Payload |
|-------|---------|
| `view` | view/fork record |
| `picked` | best fork hint or null |
| `closed` | no payload |
## getStats()
Returns `{ ...this._stats, protocol }` plus module-specific counters (pending queues, registry sizes, gossip in/out when P2P).
Local modules report hot-path counters only; P2P modules include gossip traffic when `topic` is set.
## Errors
Stable message substrings: see [`../../_shared/ERROR_CODES.md`](../../_shared/ERROR_CODES.md).
Validation helpers may throw `ValidationError` (e.g. `peer is required`, `path is required`).
### Documented `throw new Error(...)` strings
- `version must be non-negative`
## P2P
When `topic` is set, `ready()` joins Hyperswarm and opens gossip for `autobase-fork-choice/v1`.
Outbound payloads use `sendGossip` (Protomux peer map); inbound handled in `_onGossip`.
### Gossip message types
- `view-register`
## Testing
```bash
npm install && npm test
```
## Common flows
1. `registerView(forkId, version, meta)` — gossip `view-register`.
2. `pickBestFork()` — deterministic winner.
3. `listViews()` — sorted registry.
@@ -0,0 +1,21 @@
# Architecture: hyper-p2p-autobase-fork-choice
**Protocol:** `autobase-fork-choice/v1` · **P2P:** yes
## Wire
| type | payload |
|------|---------|
| `view-register` | `{ view: { forkId, version, weight, peer, at } }` |
## Selection
`pickBestFork()` — max `weight`, tie-break on `version`. `getChosenFork()` returns winning view.
## Merge
Remote view replaces local when `remote.at >= local.at` for same `forkId`.
## Composition
Run before `autobase-light-writer.flushOps` and `autobase-indexer-bus` publish.
@@ -0,0 +1,14 @@
require('bare-process/global')
const { HyperP2PAutobaseForkChoice } = require('../index.js')
async function main () {
const topic = process.argv[2] || null
const m = new HyperP2PAutobaseForkChoice({ topic })
m.attach({ async append () {} })
await m.ready()
m.registerView('fork-a', 3)
console.log(m.pickBestFork())
await m.close()
console.log('done')
}
main().catch(console.error)
@@ -0,0 +1,102 @@
require('bare-process/global')
const EventEmitter = require('bare-events')
const { assertNonEmpty } = require('../../_shared/lib/errors.js')
const { assertAutobase, attachGossip, sendGossip } = require('../../_shared/storage-gossip-base.js')
const PROTOCOL = 'autobase-fork-choice/v1'
class HyperP2PAutobaseForkChoice extends EventEmitter {
constructor (opts = {}) {
super()
this.topic = opts.topic || null
this.keyPair = opts.keyPair || require('hypercore-crypto').keyPair()
this.autobase = opts.autobase || null
this._views = new Map()
this._chosen = null
this._stats = { registered: 0, picks: 0, gossipIn: 0, gossipOut: 0 }
this.swarm = null
}
attach (autobase) {
assertAutobase(autobase)
this.autobase = autobase
return this
}
registerView (forkId, version, meta = {}) {
assertNonEmpty(forkId, 'forkId')
if (version < 0) throw new Error('version must be non-negative')
const view = {
forkId,
version,
weight: meta.weight != null ? meta.weight : version,
peer: meta.peer || null,
at: Date.now()
}
this._views.set(forkId, view)
this._stats.registered++
sendGossip(this, { type: 'view-register', view })
this._stats.gossipOut++
this.emit('view', view)
return view
}
pickBestFork () {
let best = null
for (const v of this._views.values()) {
if (!best || v.weight > best.weight || (v.weight === best.weight && v.version > best.version)) {
best = v
}
}
this._chosen = best ? best.forkId : null
this._stats.picks++
this.emit('picked', best)
return best
}
listViews () {
return [...this._views.values()].sort((a, b) => b.weight - a.weight)
}
getChosenFork () {
if (!this._chosen) return null
return this._views.get(this._chosen) || null
}
_onGossip (d) {
if (!d || d.type !== 'view-register' || !d.view) return
this._stats.gossipIn++
const existing = this._views.get(d.view.forkId)
if (!existing || (d.view.at || 0) >= (existing.at || 0)) {
this._views.set(d.view.forkId, d.view)
}
}
getStats () {
return {
...this._stats,
views: this._views.size,
chosen: this._chosen,
protocol: PROTOCOL
}
}
async ready () {
if (this.swarm || !this.topic) return this
await attachGossip(this, {
keyPair: this.keyPair,
topic: this.topic,
protocol: PROTOCOL,
onmessage: (d) => this._onGossip(d)
})
return this
}
async close () {
if (this.swarm) await this.swarm.destroy().catch(() => {})
this.swarm = null
this.emit('closed')
}
}
module.exports = { HyperP2PAutobaseForkChoice, PROTOCOL }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,27 @@
{
"name": "hyper-p2p-autobase-fork-choice",
"version": "0.3.1",
"description": "Autobase fork choice helper.",
"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",
"b4a": "^1.6.7",
"hypercore-crypto": "^3.0.0",
"protomux": "^3.0.0",
"compact-encoding": "^2.16.0"
},
"peerDependencies": {
"hyperswarm": "^4.0.0",
"bare": ">=1.0.0",
"autobase": "^7.0.0"
},
"devDependencies": { "brittle": "^3.0.0" },
"imports": {
"process": { "bare": "bare-process", "default": "process" },
"events": { "bare": "bare-events", "default": "events" }
}
}
@@ -0,0 +1,38 @@
require('bare-process/global')
const test = require('brittle')
const { HyperP2PAutobaseForkChoice, PROTOCOL } = require('../index.js')
test('exports', (t) => {
t.ok(HyperP2PAutobaseForkChoice)
t.is(PROTOCOL, 'autobase-fork-choice/v1')
})
test('registerView pickBestFork', async (t) => {
const m = new HyperP2PAutobaseForkChoice()
m.attach({ open: async () => {} })
m.registerView('f1', 2, { weight: 1 })
m.registerView('f2', 5, { weight: 10 })
const best = m.pickBestFork()
t.is(best.forkId, 'f2')
t.is(m.getChosenFork().forkId, 'f2')
await m.close()
})
test('validation', async (t) => {
const m = new HyperP2PAutobaseForkChoice()
try { m.registerView(null, 0) } catch (e) { t.ok(e) }
await m.close()
})
test('listViews', async (t) => {
const m = new HyperP2PAutobaseForkChoice()
m.registerView('a', 1)
t.is(m.listViews().length, 1)
await m.close()
})
test('getStats', async (t) => {
const m = new HyperP2PAutobaseForkChoice()
t.is(m.getStats().protocol, 'autobase-fork-choice/v1')
await m.close()
})
@@ -0,0 +1,5 @@
# Changelog
## [0.0.0-scaffold]
- Registry scaffold: file tree, load smoke tests, docs stubs
@@ -0,0 +1,41 @@
# hyper-p2p-autobase-indexer-bus
Indexer event bus with local subscribers and gossip `index-event` replication; compose with `hyper-p2p-distributed-event-bus` for cross-module routing. Hyperswarm gossip when `topic` is set.
**Category:** Storage (Autobase)
**Composes with:** `hyper-p2p-distributed-event-bus`
**Protocol:** `autobase-indexer-bus/v1`
## When to use
Derived index events must be published to all Autobase indexer peers.
## When not to use
Indexing is local-only with no shared topic.
## Quick start
```js
const { HyperP2PAutobaseIndexerBus } = require('hyper-p2p-autobase-indexer-bus')
const topic = process.argv[2] // 64-char hex or string
const mod = new HyperP2PAutobaseIndexerBus({ topic })
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
## Test
```bash
npm install && npm test
```
@@ -0,0 +1,118 @@
# API: hyper-p2p-autobase-indexer-bus
**Protocol:** `autobase-indexer-bus/v1`
**Export:** `HyperP2PAutobaseIndexerBus`
## Overview
Indexer event bus with local subscribers and gossip `index-event` replication; compose with `hyper-p2p-distributed-event-bus` for cross-module routing.
## Constructor
```js
const mod = new HyperP2PAutobaseIndexerBus(opts)
```
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `topic` | string \| Buffer \| null | null | Hyperswarm topic; gossip attaches when set |
| `keyPair` | Ed25519 KeyPair | random | Signing identity for swarm |
| `autobase` | object \| null | null | Attached autobase instance (`attach()` also supported) |
## Methods
### `attach(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `publishIndexEvent(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `subscribeIndex(…)`
- **Returns:** module-specific (see implementation)
- **Throws:**
- `Error: handler must be a function`
### `drainEvents(…)`
- **Returns:** module-specific (see implementation)
- **Throws:**
- `Error: max must be non-negative`
### `pendingEvents(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `getStats(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `ready(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `close(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
## Events
| Event | Payload |
|-------|---------|
| `index` | indexer event |
| `closed` | no payload |
## getStats()
Returns `{ ...this._stats, protocol }` plus module-specific counters (pending queues, registry sizes, gossip in/out when P2P).
Local modules report hot-path counters only; P2P modules include gossip traffic when `topic` is set.
## Errors
Stable message substrings: see [`../../_shared/ERROR_CODES.md`](../../_shared/ERROR_CODES.md).
Validation helpers may throw `ValidationError` (e.g. `peer is required`, `path is required`).
### Documented `throw new Error(...)` strings
- `handler must be a function`
- `max must be non-negative`
## P2P
When `topic` is set, `ready()` joins Hyperswarm and opens gossip for `autobase-indexer-bus/v1`.
Outbound payloads use `sendGossip` (Protomux peer map); inbound handled in `_onGossip`.
### Gossip message types
- `index-event`
## Testing
```bash
npm install && npm test
```
## Common flows
1. `publishIndexEvent(type, payload)` — queue + gossip + deliver.
2. `subscribeIndex(handler)` — local fanout.
3. `drainEvents(max)` — batch dequeue for processors.
@@ -0,0 +1,23 @@
# Architecture: hyper-p2p-autobase-indexer-bus
**Protocol:** `autobase-indexer-bus/v1` · **P2P:** yes
## Wire
| type | payload |
|------|---------|
| `index-event` | `{ evt: { type, payload, at, id } }` |
## Flow
`publishIndexEvent` → local subscribers + gossip → remote `_deliver`.
| Method | Purpose |
|--------|---------|
| `subscribeIndex(handler)` | Returns unsubscribe fn |
| `drainEvents(max)` | Remove from queue |
| `peekEvents(n)` | Non-destructive read |
## Events
`index`, `closed`
@@ -0,0 +1,14 @@
require('bare-process/global')
const { HyperP2PAutobaseIndexerBus } = require('../index.js')
async function main () {
const topic = process.argv[2] || null
const m = new HyperP2PAutobaseIndexerBus({ topic })
m.attach({ async append () {} })
await m.ready()
m.publishIndexEvent('indexed', { n: 1 })
console.log('pending', m.pendingEvents())
await m.close()
console.log('done')
}
main().catch(console.error)
@@ -0,0 +1,103 @@
require('bare-process/global')
const EventEmitter = require('bare-events')
const { assertNonEmpty } = require('../../_shared/lib/errors.js')
const { assertAutobase, attachGossip, sendGossip } = require('../../_shared/storage-gossip-base.js')
const PROTOCOL = 'autobase-indexer-bus/v1'
class HyperP2PAutobaseIndexerBus extends EventEmitter {
constructor (opts = {}) {
super()
this.topic = opts.topic || null
this.keyPair = opts.keyPair || require('hypercore-crypto').keyPair()
this.autobase = opts.autobase || null
this._queue = []
this._subs = new Set()
this._stats = { published: 0, delivered: 0, drained: 0, gossipIn: 0, gossipOut: 0 }
this.swarm = null
}
attach (autobase) {
assertAutobase(autobase)
this.autobase = autobase
return this
}
publishIndexEvent (type, payload = {}) {
assertNonEmpty(type, 'type')
const evt = { type, payload, at: Date.now(), id: this._queue.length + 1 }
this._queue.push(evt)
this._stats.published++
sendGossip(this, { type: 'index-event', evt })
this._stats.gossipOut++
this._deliver(evt)
return evt
}
subscribeIndex (handler) {
if (typeof handler !== 'function') throw new Error('handler must be a function')
this._subs.add(handler)
return () => this._subs.delete(handler)
}
_deliver (evt) {
for (const h of this._subs) {
h(evt)
this._stats.delivered++
}
this.emit('index', evt)
}
drainEvents (max = 64) {
if (max < 0) throw new Error('max must be non-negative')
const out = this._queue.splice(0, max)
this._stats.drained += out.length
return out
}
pendingEvents () {
return this._queue.length
}
peekEvents (n = 16) {
if (n < 0) throw new Error('n must be non-negative')
return this._queue.slice(0, n).map((e) => ({ ...e }))
}
_onGossip (d) {
if (!d || d.type !== 'index-event' || !d.evt) return
this._stats.gossipIn++
this._queue.push(d.evt)
this._deliver(d.evt)
}
getStats () {
return {
...this._stats,
pending: this._queue.length,
subscribers: this._subs.size,
protocol: PROTOCOL
}
}
async ready () {
if (this.swarm || !this.topic) return this
await attachGossip(this, {
keyPair: this.keyPair,
topic: this.topic,
protocol: PROTOCOL,
onmessage: (d) => this._onGossip(d)
})
return this
}
async close () {
if (this.swarm) await this.swarm.destroy().catch(() => {})
this.swarm = null
this._subs.clear()
this._queue = []
this.emit('closed')
}
}
module.exports = { HyperP2PAutobaseIndexerBus, PROTOCOL }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,27 @@
{
"name": "hyper-p2p-autobase-indexer-bus",
"version": "0.3.1",
"description": "Indexer event bus for autobase.",
"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",
"b4a": "^1.6.7",
"hypercore-crypto": "^3.0.0",
"protomux": "^3.0.0",
"compact-encoding": "^2.16.0"
},
"peerDependencies": {
"hyperswarm": "^4.0.0",
"bare": ">=1.0.0",
"autobase": "^7.0.0"
},
"devDependencies": { "brittle": "^3.0.0" },
"imports": {
"process": { "bare": "bare-process", "default": "process" },
"events": { "bare": "bare-events", "default": "events" }
}
}
@@ -0,0 +1,39 @@
require('bare-process/global')
const test = require('brittle')
const { HyperP2PAutobaseIndexerBus, PROTOCOL } = require('../index.js')
test('exports', (t) => {
t.ok(HyperP2PAutobaseIndexerBus)
t.is(PROTOCOL, 'autobase-indexer-bus/v1')
})
test('publishIndexEvent drainEvents', async (t) => {
const m = new HyperP2PAutobaseIndexerBus()
let seen = 0
m.subscribeIndex(() => { seen++ })
m.publishIndexEvent('block', { n: 1 })
const drained = m.drainEvents(10)
t.ok(drained.length >= 0)
t.ok(seen >= 1)
await m.close()
})
test('validation', async (t) => {
const m = new HyperP2PAutobaseIndexerBus()
try { m.subscribeIndex(null) } catch (e) { t.ok(e) }
try { m.publishIndexEvent(null) } catch (e) { t.ok(e) }
await m.close()
})
test('pendingEvents', async (t) => {
const m = new HyperP2PAutobaseIndexerBus()
m.publishIndexEvent('x')
t.is(m.pendingEvents(), 1)
await m.close()
})
test('getStats', async (t) => {
const m = new HyperP2PAutobaseIndexerBus()
t.is(m.getStats().protocol, 'autobase-indexer-bus/v1')
await m.close()
})
@@ -0,0 +1,5 @@
# Changelog
## [0.0.0-scaffold]
- Registry scaffold: file tree, load smoke tests, docs stubs
@@ -0,0 +1,41 @@
# hyper-p2p-autobase-light-writer
Batches lightweight Autobase append ops before flush; throttle bursts via `hyper-p2p-activity-queue` at the coordination layer. Local-only scheduling layer (no Hyperswarm join).
**Category:** Storage (Autobase)
**Composes with:** `hyper-p2p-activity-queue`
**Protocol:** `autobase-light-writer/v1`
## When to use
Clients propose many small ops that should append in bounded batches.
## When not to use
Each op must commit immediately or you need cross-peer writer leases.
## Quick start
```js
const { HyperP2PAutobaseLightWriter } = require('hyper-p2p-autobase-light-writer')
const mod = new HyperP2PAutobaseLightWriter()
mod.attach(/* Hyperautobase instance */)
await mod.ready()
// ... 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
## Test
```bash
npm install && npm test
```
@@ -0,0 +1,116 @@
# API: hyper-p2p-autobase-light-writer
**Protocol:** `autobase-light-writer/v1`
**Export:** `HyperP2PAutobaseLightWriter`
## Overview
Batches lightweight Autobase append ops before flush; throttle bursts via `hyper-p2p-activity-queue` at the coordination layer.
## Constructor
```js
const mod = new HyperP2PAutobaseLightWriter(opts)
```
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `autobase` | object \| null | null | Attached autobase instance (`attach()` also supported) |
| `maxBatch` | varies | 64 | Constructor option `maxBatch` |
## Methods
### `attach(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `proposeOp(…)`
- **Returns:** module-specific (see implementation)
- **Throws:**
- `Error: op object required`
- `Error: batch full`
### `flushOps(…)`
- **Returns:** module-specific (see implementation)
- **Throws:**
- `Error: autobase is required`
### `pendingOps(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `peekOps(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `getStats(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `ready(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `close(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
## Events
| Event | Payload |
|-------|---------|
| `propose` | staged op |
| `flush` | `{ count }` |
| `closed` | no payload |
## getStats()
Returns `{ ...this._stats, protocol }` plus module-specific counters (pending queues, registry sizes, gossip in/out when P2P).
Local modules report hot-path counters only; P2P modules include gossip traffic when `topic` is set.
## Errors
Stable message substrings: see [`../../_shared/ERROR_CODES.md`](../../_shared/ERROR_CODES.md).
Validation helpers may throw `ValidationError` (e.g. `peer is required`, `path is required`).
### Documented `throw new Error(...)` strings
- `op object required`
- `batch full`
- `autobase is required`
## P2P
Library-only: no swarm join. `ready()` resolves immediately.
`getStats().protocol` still reports the module protocol id for logging.
## Testing
```bash
npm install && npm test
```
## Common flows
1. `proposeOp(op)` — stage until `maxBatch`.
2. `flushOps()` — append all staged ops to Autobase.
3. `peekOps()` / `pendingOps()` — inspect queue.
@@ -0,0 +1,26 @@
# Architecture: hyper-p2p-autobase-light-writer
**Protocol:** `autobase-light-writer/v1` · **P2P:** no
## Role
Buffer append **proposals** then `flushOps()` to `autobase.append(op)` when attached.
## Options
`maxBatch` (default 64) — max pending ops; `proposeOp` throws when full.
## Methods
| Method | Effect |
|--------|--------|
| `proposeOp(op)` | Queue with `seq`, `at` |
| `flushOps()` | Append all via autobase |
| `rollbackOps()` | Clear queue |
| `peekOps` / `pendingOps` | Inspect |
## Events
`propose`, `flush`, `rollback`, `closed`
Requires `writer-lease` when multiple writers share one autobase.
@@ -0,0 +1,12 @@
require('bare-process/global')
const { HyperP2PAutobaseLightWriter } = require('../index.js')
async function main () {
const m = new HyperP2PAutobaseLightWriter()
m.attach({ async append () {} })
m.proposeOp({ type: 'put', key: 'x' })
console.log('pending', m.pendingOps())
await m.close()
console.log('done')
}
main().catch(console.error)
@@ -0,0 +1,77 @@
require('bare-process/global')
const EventEmitter = require('bare-events')
const { assertAutobase } = require('../../_shared/storage-gossip-base.js')
const PROTOCOL = 'autobase-light-writer/v1'
class HyperP2PAutobaseLightWriter extends EventEmitter {
constructor (opts = {}) {
super()
this.autobase = opts.autobase || null
this.maxBatch = opts.maxBatch || 64
this._ops = []
this._stats = { proposed: 0, flushed: 0, dropped: 0 }
}
attach (autobase) {
assertAutobase(autobase)
this.autobase = autobase
return this
}
proposeOp (op) {
if (!op || typeof op !== 'object') throw new Error('op object required')
if (this._ops.length >= this.maxBatch) {
this._stats.dropped++
throw new Error('batch full')
}
const entry = { ...op, at: Date.now(), seq: this._ops.length }
this._ops.push(entry)
this._stats.proposed++
this.emit('propose', entry)
return entry
}
async flushOps () {
if (!this.autobase) throw new Error('autobase is required')
const ops = this._ops.splice(0, this.maxBatch)
for (const op of ops) {
if (this.autobase.append) await this.autobase.append(op)
}
this._stats.flushed += ops.length
this.emit('flush', { count: ops.length })
return ops.length
}
pendingOps () {
return this._ops.length
}
peekOps () {
return [...this._ops]
}
rollbackOps () {
const n = this._ops.length
this._ops = []
this.emit('rollback', { count: n })
return n
}
getStats () {
return {
...this._stats,
pending: this._ops.length,
maxBatch: this.maxBatch,
protocol: PROTOCOL
}
}
async ready () { return this }
async close () {
this._ops = []
this.emit('closed')
}
}
module.exports = { HyperP2PAutobaseLightWriter, PROTOCOL }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,27 @@
{
"name": "hyper-p2p-autobase-light-writer",
"version": "0.3.1",
"description": "Light writer pattern wrapper.",
"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",
"b4a": "^1.6.7",
"hypercore-crypto": "^3.0.0",
"protomux": "^3.0.0",
"compact-encoding": "^2.16.0"
},
"peerDependencies": {
"hyperswarm": "^4.0.0",
"bare": ">=1.0.0",
"autobase": "^7.0.0"
},
"devDependencies": { "brittle": "^3.0.0" },
"imports": {
"process": { "bare": "bare-process", "default": "process" },
"events": { "bare": "bare-events", "default": "events" }
}
}
@@ -0,0 +1,39 @@
require('bare-process/global')
const test = require('brittle')
const { HyperP2PAutobaseLightWriter, PROTOCOL } = require('../index.js')
test('exports', (t) => {
t.ok(HyperP2PAutobaseLightWriter)
t.is(PROTOCOL, 'autobase-light-writer/v1')
})
test('proposeOp flushOps', async (t) => {
const appended = []
const m = new HyperP2PAutobaseLightWriter({ maxBatch: 4 })
m.attach({ append: async (op) => { appended.push(op) } })
m.proposeOp({ type: 'put' })
const n = await m.flushOps()
t.is(n, 1)
t.is(appended.length, 1)
await m.close()
})
test('batch full', async (t) => {
const m = new HyperP2PAutobaseLightWriter({ maxBatch: 1 })
m.proposeOp({ a: 1 })
try { m.proposeOp({ b: 2 }) } catch (e) { t.ok(e) }
await m.close()
})
test('validation', async (t) => {
const m = new HyperP2PAutobaseLightWriter()
try { m.proposeOp(null) } catch (e) { t.ok(e) }
await m.close()
})
test('getStats', async (t) => {
const m = new HyperP2PAutobaseLightWriter()
m.proposeOp({ x: 1 })
t.is(m.getStats().pending, 1)
await m.close()
})
@@ -0,0 +1,5 @@
# Changelog
## [0.0.0-scaffold]
- Registry scaffold: file tree, load smoke tests, docs stubs
@@ -0,0 +1,41 @@
# hyper-p2p-autobase-view-sync
Gossip-synced Autobase view version + content hash; reactive UIs can mirror via `hyper-p2p-reactive-state`. Hyperswarm gossip when `topic` is set.
**Category:** Storage (Autobase)
**Composes with:** `hyper-p2p-reactive-state`
**Protocol:** `autobase-view-sync/v1`
## When to use
Peers must agree on the latest materialized view version/hash.
## When not to use
View state is local-only or full Autobase sync replaces hash checks.
## Quick start
```js
const { HyperP2PAutobaseViewSync } = require('hyper-p2p-autobase-view-sync')
const topic = process.argv[2] // 64-char hex or string
const mod = new HyperP2PAutobaseViewSync({ topic })
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
## Test
```bash
npm install && npm test
```
@@ -0,0 +1,111 @@
# API: hyper-p2p-autobase-view-sync
**Protocol:** `autobase-view-sync/v1`
**Export:** `HyperP2PAutobaseViewSync`
## Overview
Gossip-synced Autobase view version + content hash; reactive UIs can mirror via `hyper-p2p-reactive-state`.
## Constructor
```js
const mod = new HyperP2PAutobaseViewSync(opts)
```
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `topic` | string \| Buffer \| null | null | Hyperswarm topic; gossip attaches when set |
| `keyPair` | Ed25519 KeyPair | random | Signing identity for swarm |
| `autobase` | object \| null | null | Attached autobase instance (`attach()` also supported) |
## Methods
### `attach(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `publishView(…)`
- **Returns:** module-specific (see implementation)
- **Throws:**
- `Error: version must be non-negative`
### `mergeRemoteView(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `currentView(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `getStats(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `ready(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `close(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
## Events
| Event | Payload |
|-------|---------|
| `publish` | published view |
| `merged` | merged view state |
| `closed` | no payload |
## getStats()
Returns `{ ...this._stats, protocol }` plus module-specific counters (pending queues, registry sizes, gossip in/out when P2P).
Local modules report hot-path counters only; P2P modules include gossip traffic when `topic` is set.
## Errors
Stable message substrings: see [`../../_shared/ERROR_CODES.md`](../../_shared/ERROR_CODES.md).
Validation helpers may throw `ValidationError` (e.g. `peer is required`, `path is required`).
### Documented `throw new Error(...)` strings
- `version must be non-negative`
## P2P
When `topic` is set, `ready()` joins Hyperswarm and opens gossip for `autobase-view-sync/v1`.
Outbound payloads use `sendGossip` (Protomux peer map); inbound handled in `_onGossip`.
### Gossip message types
- `view-sync`
## Testing
```bash
npm install && npm test
```
## Common flows
1. `publishView(version)` — gossip `view-sync`.
2. `mergeRemoteView(view)` — monotonic version merge.
3. `currentView()` — local snapshot.
@@ -0,0 +1,21 @@
# Architecture: hyper-p2p-autobase-view-sync
**Protocol:** `autobase-view-sync/v1` · **P2P:** yes
## Wire
| type | fields |
|------|--------|
| `view-sync` | `{ view: { version, hash, at } }` |
`hash` = `sha256("view:"+version)` (coordination digest, not Autobase proof).
## Helpers
- `isAtLeast(version)` — local caught up?
- `behindBy(version)` — blocks/versions behind target
- `mergeRemoteView` — monotonic version + hash match
## Events
`publish`, `merged`, `closed`
@@ -0,0 +1,13 @@
require('bare-process/global')
const { HyperP2PAutobaseViewSync } = require('../index.js')
async function main () {
const topic = process.argv[2] || null
const m = new HyperP2PAutobaseViewSync({ topic })
m.attach({ async append () {} })
await m.ready()
console.log(m.publishView(1))
await m.close()
console.log('done')
}
main().catch(console.error)
@@ -0,0 +1,98 @@
require('bare-process/global')
const EventEmitter = require('bare-events')
const b4a = require('b4a')
const crypto = require('hypercore-crypto')
const { assertAutobase, attachGossip, sendGossip } = require('../../_shared/storage-gossip-base.js')
const PROTOCOL = 'autobase-view-sync/v1'
class HyperP2PAutobaseViewSync extends EventEmitter {
constructor (opts = {}) {
super()
this.topic = opts.topic || null
this.keyPair = opts.keyPair || require('hypercore-crypto').keyPair()
this.autobase = opts.autobase || null
this._view = { version: 0, hash: null, at: 0 }
this._stats = { published: 0, merged: 0, gossipIn: 0, gossipOut: 0 }
this.swarm = null
}
attach (autobase) {
assertAutobase(autobase)
this.autobase = autobase
return this
}
_hashView (version) {
return b4a.toString(crypto.hash(b4a.from(`view:${version}`)), 'hex')
}
publishView (version) {
if (version < 0) throw new Error('version must be non-negative')
const view = {
version,
hash: this._hashView(version),
at: Date.now()
}
if (version >= this._view.version) this._view = view
sendGossip(this, { type: 'view-sync', view })
this._stats.published++
this._stats.gossipOut++
this.emit('publish', view)
return view
}
mergeRemoteView (view) {
if (!view || typeof view.version !== 'number') return false
if (view.version < this._view.version) return false
if (view.version === this._view.version && view.hash !== this._view.hash) {
return false
}
this._view = { ...view, mergedAt: Date.now() }
this._stats.merged++
this.emit('merged', this._view)
return true
}
currentView () {
return { ...this._view }
}
isAtLeast (version) {
return this._view.version >= version
}
behindBy (version) {
if (version < 0) throw new Error('version must be non-negative')
return Math.max(0, version - this._view.version)
}
_onGossip (d) {
if (!d || d.type !== 'view-sync' || !d.view) return
this._stats.gossipIn++
this.mergeRemoteView(d.view)
}
getStats () {
return { ...this._stats, view: this._view, protocol: PROTOCOL }
}
async ready () {
if (this.swarm || !this.topic) return this
await attachGossip(this, {
keyPair: this.keyPair,
topic: this.topic,
protocol: PROTOCOL,
onmessage: (d) => this._onGossip(d)
})
return this
}
async close () {
if (this.swarm) await this.swarm.destroy().catch(() => {})
this.swarm = null
this.emit('closed')
}
}
module.exports = { HyperP2PAutobaseViewSync, PROTOCOL }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,27 @@
{
"name": "hyper-p2p-autobase-view-sync",
"version": "0.3.1",
"description": "Autobase view synchronization.",
"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",
"b4a": "^1.6.7",
"hypercore-crypto": "^3.0.0",
"protomux": "^3.0.0",
"compact-encoding": "^2.16.0"
},
"peerDependencies": {
"hyperswarm": "^4.0.0",
"bare": ">=1.0.0",
"autobase": "^7.0.0"
},
"devDependencies": { "brittle": "^3.0.0" },
"imports": {
"process": { "bare": "bare-process", "default": "process" },
"events": { "bare": "bare-events", "default": "events" }
}
}
@@ -0,0 +1,38 @@
require('bare-process/global')
const test = require('brittle')
const { HyperP2PAutobaseViewSync, PROTOCOL } = require('../index.js')
test('exports', (t) => {
t.ok(HyperP2PAutobaseViewSync)
t.is(PROTOCOL, 'autobase-view-sync/v1')
})
test('publishView mergeRemoteView', async (t) => {
const m = new HyperP2PAutobaseViewSync()
m.attach({ open: async () => {} })
m.publishView(3)
t.is(m.currentView().version, 3)
const v5 = m.publishView(5)
t.ok(m.mergeRemoteView({ version: 5, hash: v5.hash, at: Date.now() }))
t.is(m.currentView().version, 5)
await m.close()
})
test('merge rejects regression', async (t) => {
const m = new HyperP2PAutobaseViewSync()
m.publishView(10)
t.not(m.mergeRemoteView({ version: 2, hash: 'x', at: 1 }))
await m.close()
})
test('validation', async (t) => {
const m = new HyperP2PAutobaseViewSync()
try { m.publishView(-1) } catch (e) { t.ok(e) }
await m.close()
})
test('getStats', async (t) => {
const m = new HyperP2PAutobaseViewSync()
t.is(m.getStats().protocol, 'autobase-view-sync/v1')
await m.close()
})
@@ -0,0 +1,5 @@
# Changelog
## [0.0.0-scaffold]
- Registry scaffold: file tree, load smoke tests, docs stubs
@@ -0,0 +1,41 @@
# hyper-p2p-autobase-writer-lease
TTL writer leases gossiped across peers; hard mutual exclusion layers on `hyper-p2p-distributed-lock` when needed. Hyperswarm gossip when `topic` is set.
**Category:** Storage (Autobase)
**Composes with:** `hyper-p2p-distributed-lock`
**Protocol:** `autobase-writer-lease/v1`
## When to use
Only one writer should append to Autobase for a window of time.
## When not to use
Autobase already serializes writers or leases are enforced off-chain.
## Quick start
```js
const { HyperP2PAutobaseWriterLease } = require('hyper-p2p-autobase-writer-lease')
const topic = process.argv[2] // 64-char hex or string
const mod = new HyperP2PAutobaseWriterLease({ topic })
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
## Test
```bash
npm install && npm test
```
@@ -0,0 +1,119 @@
# API: hyper-p2p-autobase-writer-lease
**Protocol:** `autobase-writer-lease/v1`
**Export:** `HyperP2PAutobaseWriterLease`
## Overview
TTL writer leases gossiped across peers; hard mutual exclusion layers on `hyper-p2p-distributed-lock` when needed.
## Constructor
```js
const mod = new HyperP2PAutobaseWriterLease(opts)
```
| Option | Type | Default | Description |
|--------|------|---------|-------------|
| `topic` | string \| Buffer \| null | null | Hyperswarm topic; gossip attaches when set |
| `keyPair` | Ed25519 KeyPair | random | Signing identity for swarm |
| `autobase` | object \| null | null | Attached autobase instance (`attach()` also supported) |
| `localWriterId` | varies | null | Constructor option `localWriterId` |
## Methods
### `attach(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `acquireLease(…)`
- **Returns:** module-specific (see implementation)
- **Throws:**
- `Error: ttlMs must be positive`
### `renewLease(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `hasLease(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `releaseLease(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `getStats(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `ready(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
### `close(…)`
- **Returns:** module-specific (see implementation)
- **Throws:** — (none in method body)
## Events
| Event | Payload |
|-------|---------|
| `lease` | lease record |
| `closed` | no payload |
## getStats()
Returns `{ ...this._stats, protocol }` plus module-specific counters (pending queues, registry sizes, gossip in/out when P2P).
Local modules report hot-path counters only; P2P modules include gossip traffic when `topic` is set.
## Errors
Stable message substrings: see [`../../_shared/ERROR_CODES.md`](../../_shared/ERROR_CODES.md).
Validation helpers may throw `ValidationError` (e.g. `peer is required`, `path is required`).
### Documented `throw new Error(...)` strings
- `ttlMs must be positive`
## P2P
When `topic` is set, `ready()` joins Hyperswarm and opens gossip for `autobase-writer-lease/v1`.
Outbound payloads use `sendGossip` (Protomux peer map); inbound handled in `_onGossip`.
### Gossip message types
- `lease-acquire`
- `lease-renew`
- `lease-release`
## Testing
```bash
npm install && npm test
```
## Common flows
1. `acquireLease(writerId, ttlMs)` — gossip `lease-acquire`.
2. `renewLease` / `releaseLease` — extend or drop lease.
3. `hasLease(writerId)` — check non-expired holder.
@@ -0,0 +1,21 @@
# Architecture: hyper-p2p-autobase-writer-lease
**Protocol:** `autobase-writer-lease/v1` · **P2P:** yes
## Wire
| type | purpose |
|------|---------|
| `lease-acquire` | New lease with `expiresAt` |
| `lease-renew` | Extend TTL |
| `lease-release` | Drop by `writerId` |
## Local API
`acquireLease`, `renewLease`, `hasLease`, `releaseLease`, `listActiveLeases`, `expireStaleLeases`
## Events
`lease`, `expired`, `closed`
Gate `light-writer.proposeOp` on `hasLease(localWriterId)`.
@@ -0,0 +1,13 @@
require('bare-process/global')
const { HyperP2PAutobaseWriterLease } = require('../index.js')
async function main () {
const topic = process.argv[2] || null
const m = new HyperP2PAutobaseWriterLease({ topic })
m.attach({ async append () {} })
await m.ready()
console.log(m.acquireLease('writer-1', 5000))
await m.close()
console.log('done')
}
main().catch(console.error)
@@ -0,0 +1,137 @@
require('bare-process/global')
const EventEmitter = require('bare-events')
const { assertNonEmpty } = require('../../_shared/lib/errors.js')
const { assertAutobase, attachGossip, sendGossip } = require('../../_shared/storage-gossip-base.js')
const PROTOCOL = 'autobase-writer-lease/v1'
class HyperP2PAutobaseWriterLease extends EventEmitter {
constructor (opts = {}) {
super()
this.topic = opts.topic || null
this.keyPair = opts.keyPair || require('hypercore-crypto').keyPair()
this.autobase = opts.autobase || null
this.localWriterId = opts.writerId || null
this._leases = new Map()
this._stats = { acquired: 0, renewed: 0, released: 0, gossipIn: 0, gossipOut: 0 }
this.swarm = null
}
attach (autobase) {
assertAutobase(autobase)
this.autobase = autobase
return this
}
acquireLease (writerId, ttlMs = 30000) {
assertNonEmpty(writerId, 'writerId')
if (ttlMs <= 0) throw new Error('ttlMs must be positive')
const now = Date.now()
const existing = this._leases.get(writerId)
if (existing && existing.expiresAt > now && existing.holder !== writerId) {
return false
}
const lease = { holder: writerId, acquiredAt: now, expiresAt: now + ttlMs, ttlMs }
this._leases.set(writerId, lease)
this._stats.acquired++
sendGossip(this, { type: 'lease-acquire', lease })
this._stats.gossipOut++
this.emit('lease', lease)
return lease
}
renewLease (writerId, ttlMs = 30000) {
const lease = this._leases.get(writerId)
if (!lease || lease.holder !== writerId) return false
lease.expiresAt = Date.now() + ttlMs
lease.ttlMs = ttlMs
this._stats.renewed++
sendGossip(this, { type: 'lease-renew', lease })
this._stats.gossipOut++
return lease
}
hasLease (writerId) {
const lease = this._leases.get(writerId)
if (!lease) return false
if (lease.expiresAt <= Date.now()) {
this._leases.delete(writerId)
return false
}
return lease.holder === writerId
}
listActiveLeases () {
const now = Date.now()
const out = []
for (const [id, lease] of this._leases) {
if (lease.expiresAt > now) out.push({ writerId: id, ...lease })
}
return out
}
expireStaleLeases () {
const now = Date.now()
let n = 0
for (const [id, lease] of this._leases) {
if (lease.expiresAt <= now) {
this._leases.delete(id)
n++
}
}
if (n) this.emit('expired', { count: n })
return n
}
releaseLease (writerId) {
const ok = this._leases.delete(writerId)
if (ok) {
this._stats.released++
sendGossip(this, { type: 'lease-release', writerId })
this._stats.gossipOut++
}
return ok
}
_onGossip (d) {
if (!d) return
this._stats.gossipIn++
if (d.type === 'lease-acquire' && d.lease) {
const l = d.lease
const existing = this._leases.get(l.holder)
if (!existing || l.acquiredAt >= existing.acquiredAt) {
this._leases.set(l.holder, l)
}
}
if (d.type === 'lease-renew' && d.lease) this._leases.set(d.lease.holder, d.lease)
if (d.type === 'lease-release') this._leases.delete(d.writerId)
}
getStats () {
return {
...this._stats,
activeLeases: this._leases.size,
protocol: PROTOCOL
}
}
async ready () {
if (this.swarm || !this.topic) return this
await attachGossip(this, {
keyPair: this.keyPair,
topic: this.topic,
protocol: PROTOCOL,
onmessage: (d) => this._onGossip(d)
})
return this
}
async close () {
if (this.swarm) await this.swarm.destroy().catch(() => {})
this.swarm = null
this._leases.clear()
this.emit('closed')
}
}
module.exports = { HyperP2PAutobaseWriterLease, PROTOCOL }
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,27 @@
{
"name": "hyper-p2p-autobase-writer-lease",
"version": "0.3.1",
"description": "Single-writer lease for autobase.",
"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",
"b4a": "^1.6.7",
"hypercore-crypto": "^3.0.0",
"protomux": "^3.0.0",
"compact-encoding": "^2.16.0"
},
"peerDependencies": {
"hyperswarm": "^4.0.0",
"bare": ">=1.0.0",
"autobase": "^7.0.0"
},
"devDependencies": { "brittle": "^3.0.0" },
"imports": {
"process": { "bare": "bare-process", "default": "process" },
"events": { "bare": "bare-events", "default": "events" }
}
}
@@ -0,0 +1,38 @@
require('bare-process/global')
const test = require('brittle')
const { HyperP2PAutobaseWriterLease, PROTOCOL } = require('../index.js')
test('exports', (t) => {
t.ok(HyperP2PAutobaseWriterLease)
t.is(PROTOCOL, 'autobase-writer-lease/v1')
})
test('acquireLease hasLease releaseLease', async (t) => {
const m = new HyperP2PAutobaseWriterLease()
m.attach({ open: async () => {} })
t.ok(m.acquireLease('w1', 60000))
t.ok(m.hasLease('w1'))
t.ok(m.releaseLease('w1'))
t.not(m.hasLease('w1'))
await m.close()
})
test('renewLease', async (t) => {
const m = new HyperP2PAutobaseWriterLease()
m.acquireLease('w2', 5000)
t.ok(m.renewLease('w2', 8000))
await m.close()
})
test('validation', async (t) => {
const m = new HyperP2PAutobaseWriterLease()
try { m.acquireLease(null) } catch (e) { t.ok(e) }
try { m.acquireLease('w', 0) } catch (e) { t.ok(e) }
await m.close()
})
test('getStats', async (t) => {
const m = new HyperP2PAutobaseWriterLease()
t.is(m.getStats().protocol, 'autobase-writer-lease/v1')
await m.close()
})