@johnhenry/browsermesh-apps 0.9.0 → 0.10.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +52 -1
- package/package.json +1 -1
- package/src/internal/torrent-store.mjs +141 -0
- package/src/mesh-bootstrap.mjs +10 -1
- package/src/mesh-torrent.mjs +476 -166
- package/src/peer-ipfs.mjs +51 -112
- package/src/peer-torrent.mjs +145 -13
package/README.md
CHANGED
|
@@ -17,6 +17,7 @@ Application layer for BrowserMesh: marketplace, chat, payments, compute orchestr
|
|
|
17
17
|
- [Sharing a `VirtualNetwork` with specific peers: mesh relay](#sharing-a-virtualnetwork-with-specific-peers-mesh-relay)
|
|
18
18
|
- [CloudStorage bucket authorization and key distribution](#cloudstorage-bucket-authorization-and-key-distribution)
|
|
19
19
|
- [CloudStorage: the ergonomic SDK](#cloudstorage-the-ergonomic-sdk)
|
|
20
|
+
- [Torrent service: durable stores, authorization and serve limits](#torrent-service-durable-stores-authorization-and-serve-limits)
|
|
20
21
|
- [Putting it all together: sync + kernel-gated mesh + relay on one connection](#putting-it-all-together-sync--kernel-gated-mesh--relay-on-one-connection)
|
|
21
22
|
- [`fetch()`/`WebSocket`-shaped mesh access: `browserMeshFetch` and `BrowserMeshWebSocket`](#fetchwebsocket-shaped-mesh-access-browsermeshfetch-and-browsermeshwebsocket)
|
|
22
23
|
- [`browserMeshFetch`](#browsermeshfetch)
|
|
@@ -59,7 +60,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
|
|
|
59
60
|
| peer-escrow | `EscrowContract`, `EscrowManager` |
|
|
60
61
|
| peer-files | `FileHost`, `FileClient` |
|
|
61
62
|
| peer-health | `HealthMonitor`, `AutoMigrator` |
|
|
62
|
-
| peer-ipfs | `IPFSStore` |
|
|
63
|
+
| peer-ipfs | `IPFSStore` (also exported as `MeshLocalCidStore`): a mesh-local content-addressed store. CIDs are SHA-256 hex digests, not IPFS CIDs, and nothing talks to the IPFS network |
|
|
63
64
|
| peer-node | `PeerNode` |
|
|
64
65
|
| peer-payments | `CreditLedger`, `WebLNProvider` |
|
|
65
66
|
| peer-registry | `PeerRegistry` |
|
|
@@ -68,6 +69,7 @@ Extracted from the private `clawser` monorepo (previously `packages/browsermesh-
|
|
|
68
69
|
| peer-terminal | `TerminalHost`, `TerminalClient` |
|
|
69
70
|
| peer-timestamp | `TimestampAuthority`, `TimestampProof` |
|
|
70
71
|
| peer-torrent | `TorrentManager` |
|
|
72
|
+
| mesh-torrent | `createTorrentService` (swarm piece exchange as a `MeshService`; injectable durable stores, `authorize` hook, serve caps) |
|
|
71
73
|
| peer-verification | `VerificationQuorum`, `Attestation` |
|
|
72
74
|
| marketplace-ui | `SkillMarketplace` |
|
|
73
75
|
| mesh-relay-host | `MeshRelayHost` |
|
|
@@ -343,6 +345,55 @@ GrantLog pattern, and the key-distribution pattern, each with pointers to
|
|
|
343
345
|
the real code, written so the *next* mesh-native service doesn't have to
|
|
344
346
|
rediscover these same design questions from scratch.
|
|
345
347
|
|
|
348
|
+
## Torrent service: durable stores, authorization and serve limits
|
|
349
|
+
|
|
350
|
+
`createTorrentService()` (`mesh-torrent.mjs`) distributes content in
|
|
351
|
+
SHA-256-addressed pieces: a downloader fetches each piece from whichever peer
|
|
352
|
+
holds it, and a finished downloader becomes a seeder. By default everything is
|
|
353
|
+
in memory and open to any peer that knows the magnet URI. These options change
|
|
354
|
+
that; all are optional.
|
|
355
|
+
|
|
356
|
+
```js
|
|
357
|
+
import { createTorrentService, attachService } from '@johnhenry/browsermesh-apps'
|
|
358
|
+
import { IndexedDBChunkStore } from '@johnhenry/browsermesh-sync'
|
|
359
|
+
|
|
360
|
+
const torrent = attachService(peerNode, undefined, createTorrentService({
|
|
361
|
+
// Durable pieces and manifests: a seeder that reloads keeps serving.
|
|
362
|
+
chunkStore: new IndexedDBChunkStore({ dbName: 'my-app-pieces' }),
|
|
363
|
+
manifestStore: myManifestStore,
|
|
364
|
+
// Who may fetch what. Return true to allow; false, a throw, or anything else denies.
|
|
365
|
+
authorize: async (fromPubKey, { kind, magnetURI, infoHash, cid, chunkCid }) =>
|
|
366
|
+
registry.checkAccess(fromPubKey, `share:${cid}`, 'read'),
|
|
367
|
+
maxConcurrentServes: 16, // chunk-responses in flight, all peers (0 = unlimited)
|
|
368
|
+
maxConcurrentServesPerPeer: 4, // ... per requesting peer
|
|
369
|
+
maxBytesPerPeerPerSec: 4 * 1024 * 1024, // served-bytes budget per peer (default 0 = unlimited)
|
|
370
|
+
maxAnnouncesPerPeerPerMinute: 30, // inbound announces accepted per peer
|
|
371
|
+
}))
|
|
372
|
+
|
|
373
|
+
await torrent.api.ensureLoaded() // after a reload: also restores listTorrents()
|
|
374
|
+
const info = await torrent.api.seed('some text') // strings are UTF-8 encoded
|
|
375
|
+
```
|
|
376
|
+
|
|
377
|
+
- **`chunkStore`** is any object with `save(cid, bytes)`, `get(cid)`,
|
|
378
|
+
`has(cid)` and `remove(cid)`, each sync or returning a Promise. The in-memory
|
|
379
|
+
`ChunkStore` and the IndexedDB-backed `IndexedDBChunkStore` from
|
|
380
|
+
`@johnhenry/browsermesh-sync` both fit; the service is tested against both.
|
|
381
|
+
- **`manifestStore`** is `{ get(magnetURI), set(magnetURI, manifest),
|
|
382
|
+
delete(magnetURI), entries() }` (sync or async). Each manifest is a small
|
|
383
|
+
JSON-safe record. It is the index of what the node holds, and a node only
|
|
384
|
+
serves pieces that one of its manifests lists, so persist both stores or
|
|
385
|
+
neither. `TorrentManager` accepts the same two options (plus `chunkSize`).
|
|
386
|
+
- Stores you pass in belong to you: `destroy()` never clears them.
|
|
387
|
+
- **`authorize`** runs before every manifest and piece is served. A refused
|
|
388
|
+
request gets exactly the reply an unknown one gets (`manifest: null` /
|
|
389
|
+
`error: 'not-found'`), so a peer cannot probe what exists. `cid` is the
|
|
390
|
+
SHA-256 hex CID of the whole content; `chunkCid` is set for `kind: 'chunk'`.
|
|
391
|
+
- Over a serve cap a requester is told `busy` (whatever it asked for) and
|
|
392
|
+
downloaders back off and retry. Caps and `authorize` never apply to the
|
|
393
|
+
downloading side.
|
|
394
|
+
- Events: `torrent:chunk-served`, `torrent:chunk-received` (as before), plus
|
|
395
|
+
`torrent:request-denied` and `torrent:serve-busy`.
|
|
396
|
+
|
|
346
397
|
## Putting it all together: sync + kernel-gated mesh + relay on one connection
|
|
347
398
|
|
|
348
399
|
Every composition layer above (`enableSync`, a `Kernel` wired via
|
package/package.json
CHANGED
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
// Shared helpers for TorrentManager (peer-torrent.mjs) and
|
|
2
|
+
// createTorrentService (mesh-torrent.mjs): byte-input normalisation, the
|
|
3
|
+
// default in-memory manifest store, and reference-counted chunk release.
|
|
4
|
+
//
|
|
5
|
+
// No browser-only imports at module level.
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Normalise anything `seed()` accepts to a `Uint8Array`.
|
|
9
|
+
*
|
|
10
|
+
* string -> UTF-8 bytes
|
|
11
|
+
* Blob -> its bytes
|
|
12
|
+
* ArrayBuffer -> a view over it
|
|
13
|
+
* TypedArray / DataView -> a Uint8Array over the same bytes (Uint8Array is returned as-is)
|
|
14
|
+
*
|
|
15
|
+
* Anything else throws a `TypeError`. It must not fall through to
|
|
16
|
+
* `new Uint8Array(x)`: for a string or a plain object that yields an EMPTY
|
|
17
|
+
* array, which silently seeded zero bytes (#195).
|
|
18
|
+
*
|
|
19
|
+
* @param {unknown} data
|
|
20
|
+
* @returns {Promise<Uint8Array>}
|
|
21
|
+
*/
|
|
22
|
+
export async function toSeedBytes(data) {
|
|
23
|
+
if (data instanceof Uint8Array) return data
|
|
24
|
+
if (typeof data === 'string') return new TextEncoder().encode(data)
|
|
25
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data)
|
|
26
|
+
if (ArrayBuffer.isView(data)) return new Uint8Array(data.buffer, data.byteOffset, data.byteLength)
|
|
27
|
+
if (typeof Blob !== 'undefined' && data instanceof Blob) return new Uint8Array(await data.arrayBuffer())
|
|
28
|
+
if (typeof SharedArrayBuffer !== 'undefined' && data instanceof SharedArrayBuffer) return new Uint8Array(data)
|
|
29
|
+
const got = data === null ? 'null' : Array.isArray(data) ? 'Array' : typeof data === 'object' ? (data.constructor?.name || 'object') : typeof data
|
|
30
|
+
throw new TypeError(
|
|
31
|
+
`seed(): data must be a string, Uint8Array, other TypedArray, ArrayBuffer or Blob (got ${got})`,
|
|
32
|
+
)
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Default `manifestStore`: a `Map` behind the async-tolerant contract
|
|
37
|
+
*
|
|
38
|
+
* get(key) -> manifest | undefined | null
|
|
39
|
+
* set(key, manifest) -> void
|
|
40
|
+
* delete(key) -> void
|
|
41
|
+
* entries() -> Iterable<[key, manifest]> | Array<[key, manifest]>
|
|
42
|
+
*
|
|
43
|
+
* (every method may be sync or return a Promise). Keys are magnet URIs;
|
|
44
|
+
* values are JSON-safe `{ infoHash, name, size, chunkSize, chunkCids, cid }`
|
|
45
|
+
* records, so a durable implementation can simply JSON-serialise them.
|
|
46
|
+
*/
|
|
47
|
+
export class MemoryManifestStore {
|
|
48
|
+
#m = new Map()
|
|
49
|
+
get(key) { return this.#m.get(key) }
|
|
50
|
+
set(key, manifest) { this.#m.set(key, manifest) }
|
|
51
|
+
delete(key) { this.#m.delete(key) }
|
|
52
|
+
entries() { return [...this.#m.entries()] }
|
|
53
|
+
clear() { this.#m.clear() }
|
|
54
|
+
get size() { return this.#m.size }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Remove the chunks of `manifest` from `chunkStore`, except any that another
|
|
59
|
+
* manifest in `manifestStore` (other than `exceptKey`) still lists -- chunks
|
|
60
|
+
* are content-addressed and shared between torrents that contain identical
|
|
61
|
+
* pieces.
|
|
62
|
+
*
|
|
63
|
+
* @param {object} chunkStore
|
|
64
|
+
* @param {object} manifestStore
|
|
65
|
+
* @param {{ chunkCids: string[] }} manifest
|
|
66
|
+
* @param {string} exceptKey magnet URI being removed
|
|
67
|
+
* @returns {Promise<number>} chunks removed
|
|
68
|
+
*/
|
|
69
|
+
export async function releaseChunks(chunkStore, manifestStore, manifest, exceptKey) {
|
|
70
|
+
const stillUsed = new Set()
|
|
71
|
+
for (const [key, other] of await manifestStore.entries()) {
|
|
72
|
+
if (key === exceptKey || !other || !Array.isArray(other.chunkCids)) continue
|
|
73
|
+
for (const cid of other.chunkCids) stillUsed.add(cid)
|
|
74
|
+
}
|
|
75
|
+
let removed = 0
|
|
76
|
+
for (const cid of new Set(manifest.chunkCids)) {
|
|
77
|
+
if (stillUsed.has(cid)) continue
|
|
78
|
+
if (await chunkStore.remove(cid)) removed++
|
|
79
|
+
}
|
|
80
|
+
return removed
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Split `bytes` into `chunkSize` pieces (zero pieces for empty input).
|
|
85
|
+
* @param {Uint8Array} bytes
|
|
86
|
+
* @param {number} chunkSize
|
|
87
|
+
* @returns {Uint8Array[]}
|
|
88
|
+
*/
|
|
89
|
+
export function splitIntoChunks(bytes, chunkSize) {
|
|
90
|
+
const pieces = []
|
|
91
|
+
for (let offset = 0; offset < bytes.length; offset += chunkSize) {
|
|
92
|
+
pieces.push(bytes.subarray(offset, Math.min(offset + chunkSize, bytes.length)))
|
|
93
|
+
}
|
|
94
|
+
return pieces
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* @param {object} store a ChunkStore-contract object (sync or async)
|
|
99
|
+
* @param {Uint8Array[]} pieces
|
|
100
|
+
* @param {(piece: Uint8Array) => Promise<string>} computeCid
|
|
101
|
+
* @returns {Promise<string[]>} the pieces' CIDs, in order. Pieces already in the store are not re-written.
|
|
102
|
+
*/
|
|
103
|
+
export async function saveChunks(store, pieces, computeCid) {
|
|
104
|
+
const cids = []
|
|
105
|
+
for (const piece of pieces) {
|
|
106
|
+
const cid = await computeCid(piece)
|
|
107
|
+
if (!(await store.has(cid))) await store.save(cid, piece)
|
|
108
|
+
cids.push(cid)
|
|
109
|
+
}
|
|
110
|
+
return cids
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Token bucket: `rate` bytes/second with a one-second burst. `take(n)` waits
|
|
115
|
+
* until `n` bytes of budget exist (a single piece larger than one second's
|
|
116
|
+
* budget waits for a full bucket, never forever). `rate <= 0` or `Infinity`
|
|
117
|
+
* disables the limit.
|
|
118
|
+
*
|
|
119
|
+
* @param {object} opts
|
|
120
|
+
* @param {number} opts.rate
|
|
121
|
+
* @param {() => number} [opts.now]
|
|
122
|
+
* @param {(ms: number) => Promise<void>} [opts.sleep]
|
|
123
|
+
*/
|
|
124
|
+
export function createByteBucket({ rate, now = Date.now, sleep = (ms) => new Promise((r) => setTimeout(r, ms)) }) {
|
|
125
|
+
const unlimited = !(rate > 0) || !Number.isFinite(rate)
|
|
126
|
+
let tokens = rate
|
|
127
|
+
let last = now()
|
|
128
|
+
return {
|
|
129
|
+
async take(bytes) {
|
|
130
|
+
if (unlimited) return
|
|
131
|
+
const need = Math.min(bytes, rate)
|
|
132
|
+
for (;;) {
|
|
133
|
+
const t = now()
|
|
134
|
+
tokens = Math.min(rate, tokens + ((t - last) / 1000) * rate)
|
|
135
|
+
last = t
|
|
136
|
+
if (tokens >= need) { tokens -= need; return }
|
|
137
|
+
await sleep(Math.ceil(((need - tokens) / rate) * 1000))
|
|
138
|
+
}
|
|
139
|
+
},
|
|
140
|
+
}
|
|
141
|
+
}
|
package/src/mesh-bootstrap.mjs
CHANGED
|
@@ -576,7 +576,9 @@ import { registerOrchestratorTools } from './mesh-orchestrator-tools.mjs'
|
|
|
576
576
|
* `node.services.get('torrent')`).
|
|
577
577
|
* @param {object} [options.torrentOptions] - Only used when `enableTorrent`.
|
|
578
578
|
* Passed straight through to `createTorrentService()`
|
|
579
|
-
* (`trackerUrl`/`chunkSize`/`envelopeType`/`manifestTimeoutMs`/`chunkTimeoutMs
|
|
579
|
+
* (`trackerUrl`/`chunkSize`/`envelopeType`/`manifestTimeoutMs`/`chunkTimeoutMs`,
|
|
580
|
+
* plus the hooks `chunkStore`/`manifestStore`/`authorize`/`maxConcurrentServes`/
|
|
581
|
+
* `maxConcurrentServesPerPeer`/`maxBytesPerPeerPerSec`/`maxAnnouncesPerPeerPerMinute`).
|
|
580
582
|
* @param {boolean} [options.enableEscrow=false] - Attach `peer-escrow.mjs`'s
|
|
581
583
|
* `createEscrowService()` (issue #117): real escrow-contract create/
|
|
582
584
|
* release/refund/dispute against `escrowOptions.creditLedger`, with
|
|
@@ -1220,6 +1222,13 @@ export async function createMeshNode(options = {}) {
|
|
|
1220
1222
|
envelopeType: torrentOptions?.envelopeType,
|
|
1221
1223
|
manifestTimeoutMs: torrentOptions?.manifestTimeoutMs,
|
|
1222
1224
|
chunkTimeoutMs: torrentOptions?.chunkTimeoutMs,
|
|
1225
|
+
chunkStore: torrentOptions?.chunkStore,
|
|
1226
|
+
manifestStore: torrentOptions?.manifestStore,
|
|
1227
|
+
authorize: torrentOptions?.authorize,
|
|
1228
|
+
maxConcurrentServes: torrentOptions?.maxConcurrentServes,
|
|
1229
|
+
maxConcurrentServesPerPeer: torrentOptions?.maxConcurrentServesPerPeer,
|
|
1230
|
+
maxBytesPerPeerPerSec: torrentOptions?.maxBytesPerPeerPerSec,
|
|
1231
|
+
maxAnnouncesPerPeerPerMinute: torrentOptions?.maxAnnouncesPerPeerPerMinute,
|
|
1223
1232
|
onLog,
|
|
1224
1233
|
})
|
|
1225
1234
|
const torrentHandle = attachService(node, servicesNetwork, torrentDescriptor)
|